// Soul Hunters - Tutorial System
// Comprehensive tutorial guide for new players

import { world, system, ItemStack, EquipmentSlot } from '@minecraft/server';

// Tutorial Step Constants
const TUTORIAL_STEPS = {
  WELCOME: 0,
  BUILD_ALTAR: 1,
  GET_WEAPON: 2,
  FIRST_DROP: 3,
  UPGRADE_WEAPON: 4
};

// Animation names for random selection
const TALK_ANIMATIONS = [
  "animation.aft_soulhunters_tutorial_npc.idle.talk_1",
  "animation.aft_soulhunters_tutorial_npc.idle.talk_2",
  "animation.aft_soulhunters_tutorial_npc.idle.talk_3"
];

// Player tutorial state storage
const TUTORIAL_STEP_PROP = "aft_soulhunters:tutorial_step";
const TUTORIAL_SUBSTEP_PROP = "aft_soulhunters:tutorial_substep";

/**
 * Tutorial Manager Class
 */
class TutorialManager {
  constructor() {
    this.setupInteractionHandler();
    this.setupScriptEventHandlers();
  }

  /**
   * Set up NPC interaction handling
   */
  setupInteractionHandler() {
    world.afterEvents.entitySpawn.subscribe((event) => {
      const { entity } = event;
      if (entity.typeId === "aft_soulhunters:tutorial_npc") {
        this.initializeTutorialNPC(entity);
      }
    });

    world.beforeEvents.playerInteractWithEntity.subscribe((event) => {
      const { player, target } = event;
      if (target.typeId === "aft_soulhunters:tutorial_npc") {
        event.cancel = true;
        system.run(() => {
          // Check if player is sneaking to reset tutorial
          if (player.isSneaking) {
            this.resetTutorial(player, target);
          } else {
            this.handleTutorialInteraction(player, target);
          }
        });
      }
    });
  }

  /**
   * Set up script event handlers
   */
  setupScriptEventHandlers() {
    system.afterEvents.scriptEventReceive.subscribe((event) => {
      const { id, sourceEntity, message } = event;
      
      // Handle tutorial reset script event
      if (id === "aft_soulhunters:reset_tutorial" && sourceEntity) {
        if (sourceEntity.typeId === "minecraft:player") {
          this.resetPlayerTutorial(sourceEntity);
        }
      }
      
      // Handle tutorial check script event  
      if (id === "aft_soulhunters:check_tutorial" && sourceEntity) {
        if (sourceEntity.typeId === "minecraft:player") {
          this.checkPlayerTutorial(sourceEntity);
        }
      }
    });
  }

  /**
   * Check player's current tutorial progress
   */
  checkPlayerTutorial(player) {
    const currentStep = this.getTutorialStep(player);
    const currentSubstep = this.getTutorialSubstep(player);
    const stepNames = ["Welcome", "Build Altar", "Get Weapon", "First Drop", "Upgrade Weapon"];
    const currentStepName = stepNames[currentStep] || "Completed";
    
    player.sendMessage("§6§l[Tutorial System]§r §eTutorial Status:");
    player.sendMessage(`§7Current Step: §f${currentStep} (${currentStepName})`);
    player.sendMessage(`§7Current Substep: §f${currentSubstep}`);
    player.sendMessage("§7Use /scriptevent aft_soulhunters:reset_tutorial to reset");
  }

  /**
   * Reset tutorial for a player via script event
   */
  resetPlayerTutorial(player) {
    player.setDynamicProperty(TUTORIAL_STEP_PROP, 0);
    player.setDynamicProperty(TUTORIAL_SUBSTEP_PROP, 0);
    
    player.sendMessage("§6§l[Tutorial System]§r §aTutorial has been reset!");
    player.sendMessage("§7Find a Tutorial NPC to start the tutorial from the beginning.");
    player.sendMessage("§7Or use the Tutorial Book to see your progress.");
  }

  /**
   * Initialize tutorial NPC with default settings
   */
  initializeTutorialNPC(npc) {
    npc.setProperty("aft_soulhunters:tutorial", "default");
    npc.setProperty("aft_soulhunters:tutorial_particles", "none");
    
    // Check if any nearby players have completed the tutorial
    const nearbyPlayers = npc.dimension.getPlayers({
      location: npc.location,
      maxDistance: 10
    });
    
    for (const player of nearbyPlayers) {
      const tutorialStep = this.getTutorialStep(player);
      if (tutorialStep > TUTORIAL_STEPS.UPGRADE_WEAPON) {
        // Player has completed tutorial, despawn this NPC immediately
        system.runTimeout(() => {
          this.handleCompletedTutorialSpawn(npc, player);
        }, 20); // Small delay to ensure NPC is fully loaded
        break;
      }
    }
  }

  /**
   * Handle when a player who completed tutorial spawns an NPC
   */
  handleCompletedTutorialSpawn(npc, player) {
    if (!npc.isValid()) return;
    
    // Send message to the player who completed tutorial
    player.sendMessage("§6§l[Tutorial NPC]§r §eYou've already completed the tutorial!");
    player.sendMessage("§7§oThe tutorial is finished. Use the Tutorial Book for reference.");
    
    // Play talk animation before despawning
    this.playTalkAnimation(npc);
    
    // Set despawn animation and remove
    system.runTimeout(() => {
      if (npc.isValid()) {
        npc.setProperty("aft_soulhunters:tutorial", "spawn_out");
        player.sendMessage("§7§o[Tutorial NPC disappearing - tutorial already completed]");
        
        // Remove after animation
        system.runTimeout(() => {
          if (npc.isValid()) {
            npc.remove();
          }
        }, 60); // 3 seconds for despawn animation
      }
    }, 40); // 2 seconds after initial message
  }

  /**
   * Reset tutorial for a player
   */
  resetTutorial(player, npc) {
    player.setDynamicProperty(TUTORIAL_STEP_PROP, 0);
    player.setDynamicProperty(TUTORIAL_SUBSTEP_PROP, 0);
    
    // Reset NPC state
    npc.setProperty("aft_soulhunters:tutorial", "default");
    npc.setProperty("aft_soulhunters:tutorial_particles", "none");
    
    player.sendMessage("§6§l[Tutorial NPC]§r §aTutorial has been reset! Let's start from the beginning.");
    player.sendMessage("§7§o(You sneaked while clicking to reset)");
    
    // Play talk animation
    this.playTalkAnimation(npc);
    
    // Start tutorial from beginning
    system.runTimeout(() => {
      this.handleWelcomeStep(player, npc, 0);
    }, 10);
  }

  /**
   * Handle player interaction with tutorial NPC
   */
  handleTutorialInteraction(player, npc) {
    const currentStep = this.getTutorialStep(player);
    const currentSubstep = this.getTutorialSubstep(player);
    
  // debug log removed
    
    // If player has completed tutorial, despawn NPC instead of offering restart
    if (currentStep > TUTORIAL_STEPS.UPGRADE_WEAPON) {
      player.sendMessage("§6§l[Tutorial NPC]§r §eYou've already completed the tutorial!");
      player.sendMessage("§7§oThe tutorial is finished. Use the Tutorial Book for reference.");
      
      // Play talk animation
      this.playTalkAnimation(npc);
      
      // Despawn the NPC
      system.runTimeout(() => {
        if (npc.isValid()) {
          npc.setProperty("aft_soulhunters:tutorial", "spawn_out");
          player.sendMessage("§7§o[Tutorial NPC disappearing - tutorial already completed]");
          
          system.runTimeout(() => {
            if (npc.isValid()) {
              npc.remove();
            }
          }, 60);
        }
      }, 40);
      return;
    }
    
    // Play talk animation when NPC speaks
    this.playTalkAnimation(npc);
    
    switch (currentStep) {
      case TUTORIAL_STEPS.WELCOME:
        this.handleWelcomeStep(player, npc, currentSubstep);
        break;
      case TUTORIAL_STEPS.BUILD_ALTAR:
        this.handleBuildAltarStep(player, npc, currentSubstep);
        break;
      case TUTORIAL_STEPS.GET_WEAPON:
        this.handleGetWeaponStep(player, npc, currentSubstep);
        break;
      case TUTORIAL_STEPS.FIRST_DROP:
        this.handleFirstDropStep(player, npc, currentSubstep);
        break;
      case TUTORIAL_STEPS.UPGRADE_WEAPON:
        this.handleUpgradeWeaponStep(player, npc, currentSubstep);
        break;
      default:
        this.handleWelcomeStep(player, npc, 0);
        break;
    }
  }

  /**
   * Play a random talk animation
   */
  playTalkAnimation(npc) {
    const randomAnim = TALK_ANIMATIONS[Math.floor(Math.random() * TALK_ANIMATIONS.length)];
    try {
      npc.runCommand(`playanimation @s ${randomAnim}`);
    } catch (e) {
      // Animation failed, continue
    }
  }

  /**
   * Step 0: Welcome Step
   */
  handleWelcomeStep(player, npc, substep) {
    switch (substep) {
      case 0:
        player.sendMessage("§6§l[Tutorial NPC]§r §eWelcome, Seeker! I'll show you how to begin your journey with Souls and Demons.");
        player.sendMessage("§7§o(Tip: Sneak + Click me anytime to restart the tutorial)");
        this.setTutorialSubstep(player, 1);
        this.setParticleState(npc, "click_continue");
        break;
      case 1:
        player.sendMessage("§6§l[Tutorial NPC]§r §eI will guide you step by step. Once you finish a step, talk to me to continue!");
        this.setTutorialSubstep(player, 2);
        break;
      case 2:
        player.sendMessage("§6§l[Tutorial NPC]§r §c§lBefore going to the next step, are you sure? You can't go back!");
        player.sendMessage("§7Click me again to continue to building the Crafting Altar.");
        this.setTutorialSubstep(player, 3);
        break;
      case 3:
        this.advanceToNextStep(player, npc);
        break;
    }
  }

  /**
   * Step 1: Build Crafting Altar
   */
  handleBuildAltarStep(player, npc, substep) {
    switch (substep) {
      case 0:
        player.sendMessage("§6§l[Tutorial NPC]§r §eFirst, you need the Crafting Altar");
        this.setParticleState(npc, "click_recipes");
        this.setTutorialSubstep(player, 1);
        break;
      case 1:
        player.sendMessage("§6§l[Tutorial NPC]§r §eHere are the recipes for the altar components.");
        player.sendMessage("§c§lIMPORTANT: §r§cI will only show these recipes once! Write them down or take a screenshot!");
        this.setParticleState(npc, "click_more_recipes");
        this.setTutorialSubstep(player, 2);
        break;
      case 2:
        player.sendMessage("§6§l[Tutorial NPC]§r §eCraft the 4 altar parts, then place them together!");
        player.sendMessage("§7§o(Remember: You can always check the Tutorial Book for recipes later)");
        this.setParticleState(npc, "all_recipes");
        player.sendMessage("§6§l[Tutorial NPC]§r §aI've given you the materials needed for the altar! Talk to me when you've built it.");
        this.setTutorialSubstep(player, 3);
        break;
      case 3:
        if (this.hasBuiltAltar(player)) {
          player.sendMessage("§6§l[Tutorial NPC]§r §aExcellent! You've built your Crafting Altar!");
          this.advanceToNextStep(player, npc);
        } else {
          player.sendMessage("§6§l[Tutorial NPC]§r §cI don't see a completed Crafting Altar nearby. Keep working on it!");
          player.sendMessage("§7Remember: Place all 4 components (Wood Table, Stone Table, Center Table, Gong) together.");
        }
        break;
    }
  }

  /**
   * Step 2: Get Soul Weapon
   */
  handleGetWeaponStep(player, npc, substep) {
    switch (substep) {
      case 0:
        player.sendMessage("§6§l[Tutorial NPC]§r §eNow you need your first weapon. Demons drop them, and spawn at night.");
        this.setTutorialSubstep(player, 1);
        break;
      case 1:
        player.sendMessage("§6§l[Tutorial NPC]§r §eDemons spawn randomly at night through portals.");
        this.setTutorialSubstep(player, 2);
        break;
      case 2:
        player.sendMessage("§6§l[Tutorial NPC]§r §eOr you can force their spawn with a Summoning Scroll, which is dropped by demons.");
        npc.setProperty("aft_soulhunters:tutorial", "scroll_out");
        this.setTutorialSubstep(player, 3);
        break;
      case 3:
        player.sendMessage("§6§l[Tutorial NPC]§r §eTo use this scroll, I need Souls. Souls drop when you slay living creatures!");
        npc.setProperty("aft_soulhunters:tutorial", "spawndark");
        this.setTutorialSubstep(player, 4);
        break;
      case 4:
        player.sendMessage("§6§l[Tutorial NPC]§r §eYour turn! Defeat it!");
        this.setParticleState(npc, "kill_monster");
        this.summonTutorialDemon(npc);
        this.setTutorialSubstep(player, 5);
        break;
      case 5:
        if (this.hasKilledTutorialDemon(player)) {
          player.sendMessage("§6§l[Tutorial NPC]§r §aWell done! You should have received a weapon. Talk to me when you're ready to continue!");
          this.advanceToNextStep(player, npc);
        } else {
          player.sendMessage("§6§l[Tutorial NPC]§r §cThe demon is still alive! Keep fighting!");
        }
        break;
    }
  }

  /**
   * Step 3: First Weapon Drop
   */
  handleFirstDropStep(player, npc, substep) {
    switch (substep) {
      case 0:
        player.sendMessage("§6§l[Tutorial NPC]§r §aExcellent! You should now have your first Soul Weapon.");
        this.setTutorialSubstep(player, 1);
        break;
      case 1:
        player.sendMessage("§6§l[Tutorial NPC]§r §eBut how do we make your weapon stronger?");
        this.setTutorialSubstep(player, 2);
        break;
      case 2:
        player.sendMessage("§6§l[Tutorial NPC]§r §eDuring the Full Moon, Dark Ones appear. They drop Crafting Scrolls and Gems.");
        this.setParticleState(npc, "shadows_drop_gems");
        this.setTutorialSubstep(player, 3);
        break;
      case 3:
        player.sendMessage("§6§l[Tutorial NPC]§r §eYour turn! Defeat it!");
        this.summonTutorialShadow(npc);
        this.setTutorialSubstep(player, 4);
        break;
      case 4:
        if (this.hasKilledTutorialShadow(player)) {
          player.sendMessage("§6§l[Tutorial NPC]§r §aPerfect! You should now have a Crafting Scroll and a Gem!");
          this.advanceToNextStep(player, npc);
        } else {
          player.sendMessage("§6§l[Tutorial NPC]§r §cThe Dark One is still alive! Keep fighting!");
        }
        break;
    }
  }

  /**
   * Step 4: Upgrade Weapon
   */
  handleUpgradeWeaponStep(player, npc, substep) {
    switch (substep) {
      case 0:
        player.sendMessage("§6§l[Tutorial NPC]§r §aPerfect! You have everything you need. Let's upgrade!");
        this.giveUpgradeMaterials(player);
        player.sendMessage("§6§l[Tutorial NPC]§r §aI've given you the upgrade materials: Iron, Redstone, and Coal!");
        this.setTutorialSubstep(player, 1);
        break;
      case 1:
        player.sendMessage("§6§l[Tutorial NPC]§r §eRead the instructions on the Crafting Scroll, place the weapon and ingredients in the altar, and right-click it.");
        this.setParticleState(npc, "use_crafting_scroll");
        this.setTutorialSubstep(player, 2);
        break;
      case 2:
        if (this.hasUpgradedWeapon(player)) {
          player.sendMessage("§6§l[Tutorial NPC]§r §a§lCongratulations! You've completed the tutorial!");
          player.sendMessage("§6§l[Tutorial NPC]§r §eGood luck on your adventure! Check out the guide book for more information.");
          
          // Mark tutorial as completed
          this.setTutorialStep(player, TUTORIAL_STEPS.UPGRADE_WEAPON + 1);
          
          this.setParticleState(npc, "good_luck");
          
          // Wait 3 seconds before playing final animation and despawning
          system.runTimeout(() => {
            npc.setProperty("aft_soulhunters:tutorial", "spawn_out");
            player.sendMessage("§7§o[Tutorial Complete - The NPC will now disappear]");
            
            // Despawn after animation finishes (5 more seconds)
            system.runTimeout(() => {
              if (npc.isValid()) {
                npc.remove();
              }
            }, 60); // 5 seconds for animation to play
          }, 60); // 3 seconds delay
        } else {
          player.sendMessage("§6§l[Tutorial NPC]§r §eUse your Crafting Scroll at the altar to upgrade your weapon!");
          player.sendMessage("§7Place your weapon, gems, and materials in the altar, then right-click to craft.");
        }
        break;
    }
  }

  /**
   * Utility Methods
   */
  getTutorialStep(player) {
    return player.getDynamicProperty(TUTORIAL_STEP_PROP) || 0;
  }

  setTutorialStep(player, step) {
    player.setDynamicProperty(TUTORIAL_STEP_PROP, step);
    player.setDynamicProperty(TUTORIAL_SUBSTEP_PROP, 0);
  }

  getTutorialSubstep(player) {
    return player.getDynamicProperty(TUTORIAL_SUBSTEP_PROP) || 0;
  }

  setTutorialSubstep(player, substep) {
    player.setDynamicProperty(TUTORIAL_SUBSTEP_PROP, substep);
  }

  advanceToNextStep(player, npc) {
    const currentStep = this.getTutorialStep(player);
    this.setTutorialStep(player, currentStep + 1);
    this.setParticleState(npc, "none");
    
    // Reset NPC state
    npc.setProperty("aft_soulhunters:tutorial", "default");
    
    // Immediately handle the next step
    system.runTimeout(() => {
      this.handleTutorialInteraction(player, npc);
    }, 10);
  }

  setParticleState(npc, state) {
    npc.setProperty("aft_soulhunters:tutorial_particles", state);
  }

  /**
   * Give missing materials for altar crafting
   */
  giveMissingMaterials(player) {
    const items = [
      new ItemStack("minecraft:iron_ingot", 1), // For wood table
      new ItemStack("minecraft:paper", 5),
      new ItemStack("minecraft:spruce_slab", 6),
      new ItemStack("minecraft:stick", 4),
      new ItemStack("minecraft:stone", 8),
      new ItemStack("minecraft:gold_nugget", 2),
      new ItemStack("minecraft:copper_ingot", 4),
      new ItemStack("minecraft:gold_ingot", 4),
      new ItemStack("aft_soulhunters:soul_item", 2)
    ];

    items.forEach(item => {
      try {
        player.getComponent("minecraft:inventory").container.addItem(item);
      } catch (e) {
        // Drop if inventory is full
        player.dimension.spawnItem(item, player.location);
      }
    });
  }

  /**
   * Give materials for weapon upgrading
   */
  giveUpgradeMaterials(player) {
    const items = [
      new ItemStack("minecraft:iron_ingot", 1),
      new ItemStack("minecraft:redstone", 1),
      new ItemStack("minecraft:coal", 1)
    ];

    items.forEach(item => {
      try {
        player.getComponent("minecraft:inventory").container.addItem(item);
      } catch (e) {
        player.dimension.spawnItem(item, player.location);
      }
    });
  }

  /**
   * Summon tutorial demon
   */
  summonTutorialDemon(npc) {
    const location = npc.location;
    const spawnLocation = {
      x: location.x + 3,
      y: location.y,
      z: location.z + 3
    };
    
    try {
      npc.dimension.spawnEntity("aft_soulhunters:tutorial_dokkaebi", spawnLocation);
    } catch (e) {
      // Failed to spawn
    }
  }

  /**
   * Summon tutorial shadow
   */
  summonTutorialShadow(npc) {
    const location = npc.location;
    const spawnLocation = {
      x: location.x + 3,
      y: location.y,
      z: location.z + 3
    };
    
    try {
      npc.dimension.spawnEntity("aft_soulhunters:tutorial_evocation_illager", spawnLocation);
    } catch (e) {
      // Failed to spawn
    }
  }

  /**
   * Check if player has built an altar nearby
   */
  hasBuiltAltar(player) {
    const altars = player.dimension.getEntities({
      type: "aft_soulhunters:crafting_altar",
      location: player.location,
      maxDistance: 20
    });
    
    return altars.length > 0;
  }

  /**
   * Check if tutorial demon was killed (simplified check)
   */
  hasKilledTutorialDemon(player) {
    // Check if player has a soul weapon (simplified)
    const inventory = player.getComponent("minecraft:inventory").container;
    for (let i = 0; i < inventory.size; i++) {
      const item = inventory.getItem(i);
      if (item && item.typeId.includes("aft_soulhunters:") && 
          (item.typeId.includes("katana") || item.typeId.includes("bow") || 
           item.typeId.includes("claw") || item.typeId.includes("sai") ||
           item.typeId.includes("hammer") || item.typeId.includes("knife") ||
           item.typeId.includes("tanto") || item.typeId.includes("fan") ||
           item.typeId.includes("shield") || item.typeId.includes("yari") ||
           item.typeId.includes("masakari") || item.typeId.includes("naginata"))) {
        return true;
      }
    }
    return false;
  }

  /**
   * Check if tutorial shadow was killed (simplified check)
   */
  hasKilledTutorialShadow(player) {
    // Check if player has a crafting scroll
    const inventory = player.getComponent("minecraft:inventory").container;
    for (let i = 0; i < inventory.size; i++) {
      const item = inventory.getItem(i);
      if (item && item.typeId.includes("aft_soulhunters:crafting_scroll")) {
        return true;
      }
    }
    return false;
  }

  /**
   * Check if player has upgraded a weapon (simplified check)
   */
  hasUpgradedWeapon(player) {
    // Check if player has a level 2+ weapon
    const inventory = player.getComponent("minecraft:inventory").container;
    for (let i = 0; i < inventory.size; i++) {
      const item = inventory.getItem(i);
      if (item && item.typeId.includes("aft_soulhunters:") && 
          (item.typeId.includes("_2") || item.typeId.includes("_3") || item.typeId.includes("_4"))) {
        return true;
      }
    }
    return false;
  }
}

// Initialize Tutorial Manager
const tutorialManager = new TutorialManager();

// Export for use in other modules
export { tutorialManager, TutorialManager };
