let mood = 0;
let moodPerClick = 1;
let purchasedUpgrades = [];
let multiplier = 1;

const upgradesContainer = document.getElementById('upgrades');
const moodCounter = document.getElementById('mood-counter');
const favicon = document.getElementById('favicon');

const upgradeInfoContainer = document.getElementById('upgrade-info');
const upgradeName = document.getElementById('upgrade-name');
const upgradeDesc = document.getElementById('upgrade-desc');
const upgradeCost = document.getElementById('upgrade-cost');

const rainRange = document.getElementById('rain-range');
const musicRange = document.getElementById('music-range');

const audioMusic = new Audio('./assets/audio/mood_not_found.mp3');
const audioRain = new Audio('./assets/audio/rain.mp3');

const upgMultiplier = document.getElementById('upg-multiplier');

function updateMoodCounter() {
  moodCounter.innerText = Math.floor(mood);

  updateUpgrades();

  if (mood < 50) {
    favicon.setAttribute('href', './assets/favicons/1.ico');
  } else if (mood < 500) {
    favicon.setAttribute('href', './assets/favicons/2.ico');
  } else if (mood < 1500) {
    favicon.setAttribute('href', './assets/favicons/3.ico');
  } else if (mood < 4000) {
    favicon.setAttribute('href', './assets/favicons/4.ico');
  } else if (mood < 80000) {
    favicon.setAttribute('href', './assets/favicons/5.ico');
  } else if (mood < 300000) {
    favicon.setAttribute('href', './assets/favicons/6.ico');
  } else if (mood < 2000000) {
    favicon.setAttribute('href', './assets/favicons/7.ico');
  }
}

function updateUpgradeInfo(upgrade) {
  upgradeInfoContainer.style.visibility = 'visible';
  upgradeName.innerText = upgrade.name;
  upgradeDesc.innerText = upgrade.description;
  upgradeCost.innerText = upgrade.cost + ' Mood';
}

function clearUpgradeInfo() {
  upgradeInfoContainer.style.visibility = 'hidden';
}

function updateUpgrades() {
  upgradesContainer.innerHTML = '';

  upgrades.slice(0, 4).forEach((upgrade) => {
    const upgradeBtn = document.createElement('button');
    upgradeBtn.id = upgrade.id;
    upgradeBtn.className = 'upgrade';
    upgradeBtn.onclick = () => purchaseUpgrade(upgrade);
    upgradeBtn.onmouseenter = () => updateUpgradeInfo(upgrade);
    upgradeBtn.onmouseleave = clearUpgradeInfo;
    upgradeBtn.oncontextmenu = () => false;
    
    if (mood < upgrade.cost) {
      upgradeBtn.style.opacity = 0.6;
      upgradeBtn.style.cursor = 'not-allowed';
    }

    const upgradeImg = document.createElement('img');
    upgradeImg.src = upgrade.image;
    upgradeImg.alt = upgrade.name + ' Upgrade';
    upgradeBtn.append(upgradeImg);

    upgradesContainer.append(upgradeBtn);
  });
}

function onLiftMoodClick() {
  mood += moodPerClick * multiplier;
  updateMoodCounter();
}

function applyUpgrade(upgrade) {
  const upgradeIndex = upgrades.indexOf(upgrade);
  purchasedUpgrades.push(upgrade.id);
  upgrades.splice(upgradeIndex, 1);

  updateMoodCounter();
  clearUpgradeInfo();
  upgrade.onPurchase();
}

function purchaseUpgrade(upgrade) {
  if (mood >= upgrade.cost) {
    mood -= upgrade.cost;
    applyUpgrade(upgrade);
  }
}

// UPGRADES
// saves

function enableSaves() {
  const saves = document.getElementById('upg-saves');
  const savesText = document.getElementById('upg-saves-text');
  saves.style.visibility = 'visible';

  let counter = 5;

  const updateCounter = () => {
    if (counter === 0) {
      const save = {
        mood,
        purchasedUpgrades,
        multiplier: +multiplier,
        musicVolume: audioMusic.volume,
        rainVolume: audioRain.volume,
      };

      localStorage.setItem('save', JSON.stringify(save));
      counter = 6;
      savesText.innerText = 'Saved!';
    } else {
      counter--;
      savesText.innerText = 'Auto save in ' + counter;
    }
  }

  setInterval(updateCounter, 1000);
  updateCounter();
}

function loadSave() {
  const save = localStorage.getItem('save');
  if (save) {
    const decodedSave = JSON.parse(save);
    mood = decodedSave.mood;
    audioMusic.volume = decodedSave.musicVolume;
    audioRain.volume = decodedSave.rainVolume;

    multiplier = decodedSave.multiplier;
    upgMultiplier.innerText = 'Multiplier: x' + multiplier.toFixed(1);

    const needUpgrades = upgrades.filter((upgrade) => decodedSave.purchasedUpgrades.includes(upgrade.id));
    needUpgrades.forEach((nUpgrade) => {
      applyUpgrade(nUpgrade);
    });

    updateMoodCounter();
  }
}

function resetProgress() {
  localStorage.removeItem('save');
  location.reload();
}

function onResetProgressClick() {
  const upgSavesReset = document.getElementById('upg-saves-reset');

  if (upgSavesReset.innerText === 'Reset progress') {
    upgSavesReset.innerText = 'Reset progress (are you sure?)';
  } else {
    resetProgress();
  }
}

// emojis

function getRandomEmoji() {
  const emojis = ['😎', '😆', '😛', '😏', '😔', '🥲', '😔', '😒', '😍', '😃', '🤓', '😊', '😁', '😄'];
  return emojis[Math.floor(Math.random() * emojis.length)];
}

function addEmoji(count = 1) {
  const upgEmojis = document.getElementById('upg-emojis');
  upgEmojis.style.display = 'block';

  for (let i = 0; i < count; i++) {
    setTimeout(() => {
      const emoji = document.createElement('span');
      emoji.innerText = getRandomEmoji();
      emoji.className = 'upg-emojis';
      upgEmojis.append(emoji);

      setInterval(() => {
        mood += Math.floor(Math.random() * 1000) * multiplier;
        emoji.innerText = getRandomEmoji();
        updateMoodCounter();

        if (purchasedUpgrades.includes('multiplier')) {
          multiplier += 0.1;
          upgMultiplier.innerText = 'Multiplier: x' + multiplier.toFixed(1);
        }
      }, 5000);
    }, Math.floor(Math.random() * 4000) + 1000);
  }
}

// rain

function enableRain() {
  audioRain.play();
  audioRain.loop = true;

  setInterval(() => {
    if (audioRain.paused) {
      audioRain.play();
      rainRange.value = audioRain.volume * 100;
    }
  }, 1000);
}

// calm_music

function enableMusic() {
  audioMusic.play();
  audioMusic.loop = true;

  setInterval(() => {
    if (audioMusic.paused) {
      audioMusic.play();
      musicRange.value = audioMusic.volume * 100;
    }
  }, 1000);
}

// mixer

function enableMixer() {
  const upgMixer = document.getElementById('upg-mixer');
  upgMixer.style.visibility = 'visible';
}

function rainRangeChange(value) {
  audioRain.volume = value / 100;
}

function musicRangeChange(value) {
  audioMusic.volume = value / 100;
}

// cuteface

function showCuteface() {
  const cuteface = document.getElementById('upg-cuteface');
  cuteface.style.visibility = 'visible';
  document.body.style.backgroundColor = '#93560e';
  moodPerClick += 600;
}

// credits

function showCredits() {
  const credits = document.getElementById('upg-credits');
  credits.style.display = 'block';
}

// cursor

function enableCursor() {
  moodPerClick += 800;
  var allElements = document.querySelectorAll('body, .btn, .click-btn');
  for (var i = 0; i < allElements.length; i++) {
    allElements[i].style.cursor = 'url("./assets/img/cursors/cursor.png"), auto';
  }
}

// multiplier

function enableMultiplier() {
  const upgMultiplier = document.getElementById('upg-multiplier');
  upgMultiplier.style.display = 'block';
}


let upgrades = [
  {
    id: 'mood_lifter',
    name: 'Mood Lifter',
    description: 'Lift your Mood. +5/click',
    image: './assets/img/upgrades/mood_lifter.png',
    cost: 50,
    onPurchase: () => moodPerClick += 5,
  },
  {
    id: 'saves',
    name: 'Free Disk Space',
    description: 'Enable saves',
    image: './assets/img/upgrades/saves.png',
    cost: 300,
    onPurchase: enableSaves,
  },
  {
    id: 'emojis',
    name: 'Emoji Thruster',
    description: 'Flying emoji. Gives some amount of mood every 5 seconds.',
    image: './assets/img/upgrades/emojis.png',
    cost: 500,
    onPurchase: addEmoji,
  },
  {
    id: 'rain',
    name: 'Rain',
    description: 'It\'s rainy outside...',
    image: './assets/img/upgrades/rain.png',
    cost: 1000,
    onPurchase: enableRain,
  },
  {
    id: 'emojis2',
    name: 'More Emoji Thrusters',
    description: 'Let the emojis flyyyyyyy-- and get some more mood',
    image: './assets/img/upgrades/emojis2.png',
    cost: 1500,
    onPurchase: () => addEmoji(5),
  },
  {
    id: 'calm_music',
    name: 'Old Radio',
    description: 'Listen to the hand-made music',
    image: './assets/img/upgrades/calm_music.png',
    cost: 3000,
    onPurchase: enableMusic,
  },
  {
    id: 'cursor',
    name: 'Cursor',
    description: 'Click Clack. +800 mood/click',
    image: './assets/img/upgrades/cursor.png',
    cost: 4000,
    onPurchase: enableCursor,
  },
  {
    id: 'mixer',
    name: 'Mixer',
    description: 'Control the sounds',
    image: './assets/img/upgrades/mixer.png',
    cost: 50000,
    onPurchase: enableMixer,
  },
  {
    id: 'cuteface',
    name: 'Cuteface',
    description: 'A little bit... unusual background... no?..',
    image: './assets/img/upgrades/cuteface.png',
    cost: 80000,
    onPurchase: showCuteface,
  },
  {
    id: 'emojis3',
    name: 'Even More Emoji Thrusters',
    description: 'mayhem but more mood',
    image: './assets/img/upgrades/emojis3.png',
    cost: 100000,
    onPurchase: () => addEmoji(20),
  },
  {
    id: 'multiplier',
    name: 'Mood Multiplier',
    description: 'Even more mood with time',
    image: './assets/img/upgrades/multiplier.png',
    cost: 300000,
    onPurchase: enableMultiplier,
  },
  {
    id: 'credits',
    name: 'The End',
    description: 'it\'s alpha',
    image: './assets/img/upgrades/credits.png',
    cost: 15000000,
    onPurchase: showCredits,
  },
];

loadSave();
updateUpgrades();
