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

const killObjective = "player_kills";
const deathObjective = "player_deaths";
const moneyObjective = "Money"; // ← reward scoreboard
// === Added Ender Dragon Kill Reward ===
const TARGET_LOCATION = { x: 0, y: 64, z: 0 }; // example target location, adjust as needed
const RADIUS = 100; // example radius, adjust as needed
const SCOREBOARD = moneyObjective;
const REWARD_AMOUNT = 45000; // reward amount for killing the dragon


function setupScoreboard() {
  const objectives = world.scoreboard.getObjectives().map(obj => obj.id);
  if (!objectives.includes(killObjective)) {
    world.scoreboard.addObjective(killObjective, "Player Kills");
  }
  if (!objectives.includes(deathObjective)) {
    world.scoreboard.addObjective(deathObjective, "Player Deaths");
  }
}

const hostileMobs = [
  "minecraft:zombie", "minecraft:skeleton", "minecraft:creeper", "minecraft:spider",
  "minecraft:wither", "minecraft:blaze", "minecraft:pillager", "minecraft:evocation_illager",
  "minecraft:vindicator", "minecraft:ravager", "minecraft:stray", "minecraft:drowned",
  "minecraft:warden", "minecraft:ender_dragon", "minecraft:bogged", "minecraft:husk",
  "minecraft:wither_skeleton", "minecraft:witch", "minecraft:breeze", "minecraft:cave_spider",
];

const lastDamager = new Map();

world.afterEvents.entityHurt.subscribe(event => {
  const { hurtEntity, damageSource } = event;
  const damager = damageSource?.damagingEntity;

  if (hurtEntity && damager?.typeId === "minecraft:player") {
    lastDamager.set(hurtEntity.id, {
      player: damager,
      time: Date.now()
    });
  }
});

function cleanupLastDamager() {
  const now = Date.now();
  for (const [entityId, data] of lastDamager.entries()) {
    if (now - data.time > 15000) {
      lastDamager.delete(entityId);
    }
  }
}

world.afterEvents.entityDie.subscribe(event => {
  const { deadEntity, damageSource } = event;
  if (!deadEntity) return;

  let killer = damageSource?.damagingEntity;

  if (!killer) {
    const last = lastDamager.get(deadEntity.id);
    if (last && (Date.now() - last.time) < 15000) {
      killer = last.player;
    }
  }

  // ✅ Always increase death count if the entity is a player
  if (deadEntity.typeId === "minecraft:player") {
    const deathScore = world.scoreboard.getObjective(deathObjective);
    if (deathScore) {
      const currentDeaths = deathScore.getScore(deadEntity) ?? 0;
      const newDeaths = currentDeaths + 1;
      deathScore.setScore(deadEntity, newDeaths);

      // --- Death Penalty (every 50 deaths, scaling) ---
      const moneyScore = world.scoreboard.getObjective(moneyObjective);
      if (moneyScore && newDeaths % 50 === 0) {
        const milestone = newDeaths / 50; // 1 = 50 deaths, 2 = 100 deaths...
        const penalty = 5000 + (milestone - 1) * 3000; // 5k, 8k, 11k...
        const currentMoney = moneyScore.getScore(deadEntity.scoreboardIdentity) ?? 0;
        moneyScore.setScore(deadEntity.scoreboardIdentity, Math.max(0, currentMoney - penalty));
        world.sendMessage(`§c${deadEntity.name} has died §l${newDeaths}§r§c times and lost §a$${penalty.toLocaleString()}§c!`);
        deadEntity.playSound("random.break");
      }
    }

    // ✅ Send death message
    if (killer) {
      const killerId = killer.typeId;

      if (killerId === "minecraft:player") {
        const killerName = killer.name;
        deadEntity.sendMessage(`§cYou were killed by §l${killerName}§r§c.`);

        // ✅ ADDITION: Reward system
        try {
          const moneyScore = world.scoreboard.getObjective(moneyObjective);
          if (moneyScore) {
            const current = moneyScore.getScore(killer.scoreboardIdentity) ?? 0;
            moneyScore.setScore(killer.scoreboardIdentity, current + 5000);
          }
        } catch (err) {
          console.warn("[Money Reward] Failed to give money:", err);
        }

        // ✅ Sound + message
        killer.runCommandAsync("playsound random.orb");
        killer.sendMessage(`§6You killed §c${deadEntity.name} §6and earned §a$5000§r§6!`);
      } else if (hostileMobs.includes(killerId)) {
        const mobName = killerId
          .replace("minecraft:", "")
          .split("_")
          .map(w => w[0].toUpperCase() + w.slice(1))
          .join(" ");
        deadEntity.sendMessage(`§cYou were killed by a §l${mobName}§r§c.`);
      }
    }
  }

  // ✅ Only increase kill count for players killing players or hostile mobs
if (killer?.typeId === "minecraft:player") {
  if (deadEntity.typeId === "minecraft:player" || hostileMobs.includes(deadEntity.typeId)) {
    const killScore = world.scoreboard.getObjective(killObjective);
    if (killScore) {
      const currentKills = killScore.getScore(killer) ?? 0;
      const newKills = currentKills + 1;
      killScore.setScore(killer, newKills);

      // --- Kill Milestone Reward (every 600 kills, scaling) ---
      const moneyScore = world.scoreboard.getObjective(moneyObjective);
      if (moneyScore && newKills % 600 === 0) {
        const milestone = newKills / 600; // 1 = 600 kills, 2 = 1200 kills...
        const reward = 100000 + (milestone - 1) * 30000; // 100k, 130k, 160k...
        const currentMoney = moneyScore.getScore(killer.scoreboardIdentity) ?? 0;
        moneyScore.setScore(killer.scoreboardIdentity, currentMoney + reward);
        world.sendMessage(`§6${killer.name} reached §l${newKills}§r§6 kills and earned §a$${reward.toLocaleString()}§6!`);
        killer.playSound("random.levelup");
      }
    }
  }
}

  // === Ender Dragon Reward
  if (deadEntity.typeId === "minecraft:ender_dragon" && deadEntity.dimension.id === "minecraft:the_end") {
    for (const player of deadEntity.dimension.getPlayers()) {
      const dx = player.location.x - TARGET_LOCATION.x;
      const dy = player.location.y - TARGET_LOCATION.y;
      const dz = player.location.z - TARGET_LOCATION.z;
      const distSq = dx * dx + dy * dy + dz * dz;

      if (distSq <= RADIUS * RADIUS) {
        player.runCommandAsync(`scoreboard players add "${player.name}" ${moneyObjective} ${REWARD_AMOUNT}`);
        player.sendMessage(`§aYou earned §a§l$${REWARD_AMOUNT}§r§a for defeating the Ender Dragon!`);
        player.playSound("random.levelup");
      }
    }
  }

  lastDamager.delete(deadEntity.id);
});

system.runInterval(() => cleanupLastDamager(), 60 * 1000);
system.run(setupScoreboard);