import { world, system } from "@minecraft/server";
import { fo } from './utilities/fo_constants.js';




export function initCredits() {

  const interval = 60; 

  
  const creditKeys = [
    "Fo.Credits01",
    "Fo.Credits02",
    "Fo.Credits03",
    "Fo.Credits04",
    "Fo.Credits05",
    "Fo.Credits06",
    "Fo.Credits07",
    "Fo.Credits08", 
    "Fo.Credits09",
    "Fo.Credits10",
    "Fo.Credits11"
  ];

  
  function createExperienceOrbExplosion(player) {
    const overworld = fo.overworld;

    
    for (let i = 0; i < 120; i++) { 
      system.runTimeout(() => {
        
        const explosionPos = {
          x: player.location.x + (Math.random() - 0.5) * 20, 
          y: player.location.y + 15,
          z: player.location.z + (Math.random() - 0.5) * 20  
        };
        overworld.spawnEntity("minecraft:xp_orb", explosionPos);
      }, i)
    }

    
  }

  
  async function showCredits() {
    let delay = 230; 

    world.scoreboard.getObjective("Online").addScore("Kolveman", 0) 

    for (let i = 0; i < creditKeys.length; i++) {
      let key = creditKeys[i];

      
      if (i === 7 && fo.endlessMode) { 
        key = "Fo.Credits08b"; 
      }

      world.sendMessage({ translate: key }); 

      if (i === (creditKeys.length - 1)) world.scoreboard.getObjective("Online").removeParticipant("Kolveman"); 

      await new Promise(resolve => system.runTimeout(resolve, delay));
    }
  }

  
  function playVictorySound() {

    
    world.playMusic("challenge_complete")
  }

  
  function checkScoreAndShowCredits() {
    if (!fo.creditsToggle) return;

    const counterScore = fo.forebodingScore;

    
    if (counterScore >= (fo.scoreChapter6 - interval) && counterScore < fo.scoreChapter6) {
      system.runTimeout(showCredits, 240);
      playVictorySound();  

      
      const players = world.getPlayers();
      for (const player of players) {
        createExperienceOrbExplosion(player);
      }

    }
  }

  
  system.runInterval(checkScoreAndShowCredits, interval);  

}
