import { world, system } from "@minecraft/server";
import { ActionFormData } from "@minecraft/server-ui";

// Trigger on NPC right-click or hit
world.afterEvents.playerInteractWithEntity.subscribe(event => {
  const { player, target } = event;
  if (!target || target.typeId !== "npc:npc_custom") return;
  rankMenu(player);
  player.playSound("random.pop2");
});

world.afterEvents.entityHitEntity.subscribe(event => {
  const { damagingEntity, hitEntity } = event;
  if (!(damagingEntity?.typeId === "minecraft:player")) return;
  if (!hitEntity || hitEntity.typeId !== "npc:npc_custom") return;
  rankMenu(damagingEntity);
  damagingEntity.playSound("random.pop2");
});


// Rank definitions
const rankData = {
  Warrior: {
    price: 500000,
    tag: "gwim:Warrior",
    display: "§l§cWarrior§r"
  },
  Miner: {
    price: 600000,
    tag: "gwim:Miner",
    display: "§l§aMiner§r"
  },
  Healer: {
    price: 300000,
    tag: "gwim:Healer",
    display: "§l§dHealer§r"
  },
  VIP: {
    price: 5000000,
    tag: "VIPPurchased",
    display: "§l§eVIP§r"
  },
};

const allRankTags = Object.values(rankData).map(r => r.tag);

// RANK INFO TEXT
const rankInfoText = `
§8§l✦ RANK PERKS & BONUSES ✦\n§r

§l§c• Warrior§r\n§7Permanent §cStrength IV§7 & §9Resistance III§r\n
§l§a• Miner§r\n§7Permanent §eHaste V§r\n
§l§d• Healer§r\n§7Permanent §dRegeneration V§r\n
§l§e• VIP§r\n§7Access to the exclusive §eVIP Zone§r\n
§l§e• VIP+§r\n§7Permanent §eHaste IV§7 & §9Resistance III§r\n
§l§b• Elite§r\n§7Permanent §dRegeneration V§7, §cStrength IV§7, §9Resistance III§7 & §eHaste IV§r\n
§l§b• Elite+§r\n§7All Elite perks §8+ §a3×3×3 Mining Ability§r\n
§l§d• ||GOD||§r\n§7All Elite+ perks §8+ §eFlying Ability§r\n

§8§m────────────────────────────\n

§8§l✦ RANK UNLOCK GUIDE ✦\n§r
§7To unlock premium ranks, start by buying the §eVIP§7 rank:\n
§6• §f80M – 200M Money §8→ \n
§6• §f200M – 400M Money §8→ \n
§6• §f400M - 1B Money §8→ \n
§6• §f1B+ Money §8→ \n

`;

function clearPlayerRanks(player) {
  for (const tag of allRankTags) {
    if (player.hasTag(tag)) player.removeTag(tag);
  }
}

function getCurrentRank(player) {
  for (const [name, data] of Object.entries(rankData)) {
    if (player.hasTag(data.tag)) {
      return { name, data };
    }
  }
  return null;
}

function showRankInfo(player) {
  const infoForm = new ActionFormData()
    .title("§lRank Info")
    .body(rankInfoText)
    .button('§l§cBack', "textures/ui/arrow_left")

  infoForm.show(player).then(() => rankMenu(player));
}

export function rankMenu(player) {
  const form = new ActionFormData()
    .title("§lRank Menu")
    .body("Buy one of the ranks below:\n(You can only have one rank at a time)")
    .button("§lRank Info\n§r§7[ Click to View ]") // Info
    .button("§c§lWarrior Rank\n§rPrice:§a $500,000")
    .button("§a§lMiner Rank\n§rPrice:§a $600,000")
    .button("§d§lHealer Rank\n§rPrice:§a $300,000")
    .button("§e§lVIP Rank\n§rPrice:§a $5,000,000")
    .button("§lClear My Rank\n§c[Refund]");

  form.show(player).then(res => {
    if (res.canceled) return;

    if (res.selection === 0) return showRankInfo(player); // Info button

    const adjustedSelection = res.selection - 1;
    const moneyObjective = world.scoreboard.getObjective("Money");
    if (!moneyObjective) {
      player.sendMessage("§cError: 'Money' scoreboard not found!");
      return;
    }

    const identity = player.scoreboardIdentity;
    const currentMoney = moneyObjective.getScore(identity) ?? 0;
    const currentRank = getCurrentRank(player);

    // Sell current rank
    if (adjustedSelection === 4) {
      if (!currentRank) {
        player.playSound("note.bass");
        player.sendMessage("§cYou don't have a rank to sell!");
        return;
      }

      clearPlayerRanks(player);
      moneyObjective.setScore(identity, currentMoney + currentRank.data.price);
      player.playSound("random.orb");
      player.sendMessage(`§eYou sold your ${currentRank.data.display}§e rank for $${currentRank.data.price}.`);
      return;
    }

    const selectedRankName = Object.keys(rankData)[adjustedSelection];
    const selectedRank = rankData[selectedRankName];

    if (player.hasTag(selectedRank.tag)) {
      player.playSound("note.bass");
      player.sendMessage(`§cYou already own the ${selectedRank.display}§c rank!`);
      return;
    }

    // Evaluate total money including refund (if any)
    let totalMoney = currentMoney;
    if (currentRank) {
      totalMoney += currentRank.data.price;
    }

    // Check if affordable
    if (totalMoney < selectedRank.price) {
      player.playSound("note.bass");
      player.sendMessage("§cNot enough money!");
      return;
    }

    // Proceed: Remove old rank if any
    if (currentRank) {
      clearPlayerRanks(player);
      player.sendMessage(`§8§oYour old rank ${currentRank.data.display}§8§o was sold for $${currentRank.data.price}.`);
    }

    // Deduct cost and apply new rank
    const finalMoney = totalMoney - selectedRank.price;
    moneyObjective.setScore(identity, finalMoney);
    player.addTag(selectedRank.tag);
    player.playSound("random.orb");
    player.sendMessage(`§aYou have purchased the ${selectedRank.display}§a rank for $${selectedRank.price}!`);
  });
}