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

// 📌 Phase biome names
const phaseNames = {
  1: "Plains Biome",
  2: "Underground",
  3: "Deep Cave",
  4: "Desert",
  5: "Snowy",
  6: "Jungle",
  7: "BarrenLands",
  8: "Ocean",
  9: "Pale Garden",
  10: "Swamp & Cherry",
  11: "Mansion",
  12: "Nether",
  13: "Trial Chamber",
  14: "Ancient City",
  15: "Stronghold",
  16: "The Infinite"
};

// 📌 Phase blocks
const phaseBlocks = {
  1: ["grass_block","dirt","mycelium","dirt_with_roots","oak_log","birch_log","oak_leaves","birch_leaves","hay_block","clay","bone_block","gravel","pumpkin","melon_block","composter","beehive"],
  2: ["stone","gravel","iron_ore","copper_ore","oak_log","oak_planks","oak_fence","coal_ore","tuff","dripstone_block","raw_iron_block","raw_copper_block"],
  3: ["big_dripleaf","stone","small_dripleaf_block","deepslate","copper_ore","granite","andesite","diorite","dripstone_block","cave_vines","pointed_dripstone","amethyst_block","budding_amethyst","amethyst_cluster","gravel","calcite","clay","smooth_basalt"],
  4: ["sand","sandstone","stone","deadbush","cactus","deepslate","deepslate_coal_ore","deepslate_iron_ore","deepslate_lapis_ore","deepslate_gold_ore","coal_ore","iron_ore","lapis_ore","redstone_ore","suspicious_sand","suspicious_gravel","tnt","stone_pressure_plate","chiseled_sandstone","cut_sandstone"],
  5: ["snow","powder_snow","ice","packed_ice","blue_ice","grass_block","podzol","dirt","stone","granite","diorite","andesite","deepslate","deepslate_iron_ore","deepslate_coal_ore","deepslate_lapis_ore","deepslate_redstone_ore","deepslate_gold_ore","iron_ore","coal_ore","lapis_ore","redstone_ore","gold_ore","spruce_log","spruce_leaves","snow_layer"],
  6: ["grass_block","honey_block","honeycomb_block","melon_block","bee_nest","big_dripleaf","bamboo","dirt","jungle_log","jungle_leaves","cobblestone","mossy_cobblestone","coal_ore","iron_ore","redstone_ore","lapis_ore","gold_ore","diamond_ore","deepslate_coal_ore","deepslate_iron_ore","deepslate_redstone_ore","deepslate_lapis_ore","deepslate_gold_ore","deepslate_diamond_ore","cocoa"],
  7: ["red_sand","acacia_leaves","acacia_log","dark_oak_planks","dark_oak_fence","clay","red_sandstone","deepslate","deepslate_coal_ore","deepslate_iron_ore","deepslate_lapis_ore","deepslate_redstone_ore","deepslate_gold_ore","deepslate_diamond_ore","coal_ore","iron_ore","lapis_ore","redstone_ore","gold_ore","diamond_ore","suspicious_sand","suspicious_gravel","terracotta","gold_block"],
  8: ["prismarine","tube_coral","brain_coral","bubble_coral","fire_coral","horn_coral","dirt","sand","gravel","prismarine_bricks","dark_prismarine","sea_lantern","sponge","wet_sponge","kelp"],
  9: ["grass_block","pale_oak_log","pale_moss_block","pale_hanging_moss","pale_oak_leaves","pale_oak_wood","resin_block","resin_bricks","resin_clump","open_eyeblossom","closed_eyeblossom","creaking_heart","pale_oak_sapling","deepslate","stone","iron_ore","coal_ore"],
  10: ["grass_block","dirt","dirt_with_roots","bone_block","mangrove_log","cherry_log","ochre_froglight","verdant_froglight","pearlescent_froglight","mangrove_leaves","cherry_leaves","mud_bricks","mud","packed_mud","sand","water","pink_petals","mangrove_roots","muddy_mangrove_roots","mangrove_propagule","cherry_sapling"],
  11: ["oak_planks","dark_oak_planks","dark_oak_stairs","cobblestone","dark_oak_log","glass_pane","dark_oak_leaves","grass_block","dirt","bee_nest","brown_mushroom_block","emerald_ore","red_mushroom_block","bookshelf","lectern","fletching_table","cartography_table"],
  12: ["netherrack","ancient_debris","quartz_ore","crimson_nylium","warped_nylium","weeping_vines","lava","nether_brick","red_nether_brick","soul_sand","soul_soil","basalt","blackstone","polished_blackstone","gilded_blackstone","gold_nugget","magma","glowstone","shroomlight","crimson_stem","warped_stem"],
  13: ["deepslate","copper_bulb","copper_block","cut_copper","copper_grate","chiseled_copper","tuff","tuff_bricks","chiseled_tuff_bricks","polished_tuff","deepslate_bricks","gravel","suspicious_gravel","chiseled_nether_bricks","bone_block","stone_pressure_plate","crafter","heavy_core","copper_door","copper_trapdoor"],
  14: ["deepslate","stone","calibrated_sculk_sensor","sculk_sensor","sculk_catalyst","sculk","sculk_vein","copper_ore","redstone_ore","gravel","bone_block","polished_deepslate","deepslate_bricks","chiseled_deepslate","deepslate_tiles","chest","sculk_shrieker","reinforced_deepslate"],
  15: ["deepslate","stone_bricks","mossy_stone_bricks","cracked_stone_bricks","stone","dirt","gravel","suspicious_gravel","iron_bars","bookshelf","oak_fence","oak_planks","oak_door","iron_door","chest","end_portal_frame"],
  16: ["grass_block","dirt","mycelium","stone","copper_ore","iron_ore","coal_ore","deepslate","diamond_ore","redstone_ore","lapis_ore","nether_brick","end_stone","purpur_block","chorus_plant","chorus_flower","end_rod","obsidian"]
};

// 📌 Phase mobs
const phaseMobs = {
  1: ["cow","chicken","pig","mooshroom","sheep","armadillo","goat"],
  2: ["spider","skeleton","cow","pig","chicken"],
  3: ["zombie","skeleton","axolotl","creeper","bat","slime","glow_squid"],
  4: ["rabbit","husk","creeper","spider","camel","skeleton"],
  5: ["stray","skeleton_horse","zombie_horse","enderman","polar_bear","fox","skeleton"],
  6: ["ocelot","parrot","bee","cave_spider","spider","creeper","skeleton","phantom","panda"],
  7: ["rabbit","husk","creeper","spider","cave_spider","camel","armadillo"],
  8: ["dolphin","cod","salmon","tropical_fish","squid","glow_squid","drowned","guardian","elder_guardian"],
  9: ["zombie","skeleton","skeleton_horse","spider","creeper","wolf","cow","pig","chicken","sniffer","camel","creaking"],
  10: ["bogged","sniffer","frog","tadpole","slime","cow","sheep","chicken"],
  11: ["zombie","skeleton","vindicator","ravager","creeper","stray","husk","spider","pillager","phantom","evocation_illager","iron_golem","allay"],
  12: ["zombie_piglin","magma_cube","piglin","wither_skeleton","ghast","blaze","enderman","piglin_brute","hoglin","strider"],
  13: ["zombie","skeleton","zombie_villager","breeze","bogged","spider","creeper","husk","stray","zombie_horse"],
  14: ["zombie","skeleton","axolotl","creeper","zombie_villager","spider","bat","warden"],
  15: ["skeleton","zombie","creeper","bat","spider","silverfish"],
  16: ["cow","chicken","pig","sheep","zombie","skeleton","creeper","shulker","endermite"]
};


// 📌 Difficulty
const DifficultyNames = ["Easy", "Normal", "Hard", "Super Hard", "Super Super Hard", "Extra Ordinary Hard"];

// 📌 OneBlock state
let oneblockData = {
  x: 0, y: 0, z: 0,
  phase: 1,
  blockCount: 0,
  active: false,
  upgrading: false,
  welcomeEntities: [],
  currentBiomeScoreboardName: "",
  difficulty: 1 // Default Normal
};

// ============================
// 🔹 Persistence
// ============================
function saveOneblockData() {
  try {
    const clone = { ...oneblockData };
    clone.welcomeEntities = [];
    world.setDynamicProperty("oneblock:data", JSON.stringify(clone));
  } catch (e) { console.warn("Save error:", e); }
}
function loadOneblockData() {
  try {
    const raw = world.getDynamicProperty("oneblock:data");
    if (raw) {
      const saved = JSON.parse(raw);
      oneblockData = { ...oneblockData, ...saved, welcomeEntities: [] };

      if (oneblockData.active) {
        const dimension = world.getDimension("overworld");
        applyDifficultyRules(dimension); // Ensure rules are applied on load
        system.runTimeout(() => {
          const texts = [
            "§aEnjoy The Game!",
            `§bRunning Biome: ${phaseNames[oneblockData.phase]}`,
            "§dWelcome To Gaming Boy Oneblock",
            "§e⬇ Break This Block ⬇"
          ];
          texts.forEach((txt, i) => {
            try {
              const ent = dimension.spawnEntity("oneblock:floating_text", {
                x: oneblockData.x + 0.5,
                y: oneblockData.y + 2.5 + i * 0.5,
                z: oneblockData.z + 0.5
              });
              ent.nameTag = txt;
              ent.addTag("oneblock_welcome");
              oneblockData.welcomeEntities.push(ent);
            } catch {}
          });
          setBiomeScoreboard(dimension);
        }, 40);
      }
    }
  } catch (e) { console.warn("Load error:", e); }
}

// ============================
// 🔹 Utility
// ============================
function clearWelcomeTexts() {
  for (let ent of oneblockData.welcomeEntities) {
    try { if (ent?.isValid()) ent.kill(); } catch {}
  }
  oneblockData.welcomeEntities = [];
}
function updateWelcomeTexts() {
  if (oneblockData.welcomeEntities.length >= 2) {
    const biomeLine = oneblockData.welcomeEntities[1];
    if (biomeLine?.isValid()) {
      biomeLine.nameTag = `§bRunning Biome: ${phaseNames[oneblockData.phase]}`;
    }
  }
}
function clearOldBiomeScoreboard(dimension) {
  if (oneblockData.currentBiomeScoreboardName) {
    try {
      dimension.runCommand(`scoreboard players reset "${oneblockData.currentBiomeScoreboardName}" oneblock_count`);
    } catch {}
    oneblockData.currentBiomeScoreboardName = "";
  }
}
function setBiomeScoreboard(dimension) {
  clearOldBiomeScoreboard(dimension);
  const name = `§eBiome: §a${phaseNames[oneblockData.phase]}`;
  try {
    dimension.runCommand(`scoreboard players set "${name}" oneblock_count 0`);
    oneblockData.currentBiomeScoreboardName = name;
  } catch {}
}

// ============================
// 🔹 World Init
// ============================
world.afterEvents.worldInitialize.subscribe(() => {
  const overworld = world.getDimension("overworld");
  try { overworld.runCommand('scoreboard objectives add oneblock_count dummy "§b§lGaming Boy OB"'); } catch {}
  loadOneblockData();

  // 🔹 Watchdog: Auto-fix empty OneBlock (Air, Flowing Liquids, Falling Blocks)
  system.runInterval(() => {
    if (!oneblockData.active || oneblockData.upgrading) return;
    
    // 🔹 Difficulty Effects Tick
    applyDifficultyTick(overworld);

    const block = overworld.getBlock({ x: oneblockData.x, y: oneblockData.y, z: oneblockData.z });
    if (!block) return;

    if (block.typeId === "minecraft:air" || block.typeId === "minecraft:flowing_lava" || block.typeId === "minecraft:flowing_water") {
      const blocks = phaseBlocks[oneblockData.phase];
      if (blocks?.length) {
        const randomBlock = blocks[Math.floor(Math.random() * blocks.length)];
        try { overworld.runCommand(`setblock ${oneblockData.x} ${oneblockData.y} ${oneblockData.z} ${randomBlock}`); } catch {}
      }
    }
  }, 20);
});

// ============================
// 🔹 Remote UI
// ============================
world.afterEvents.itemUse.subscribe(event => {
  const { itemStack, source: player } = event;
  if (itemStack.typeId !== "set:oneblock_remote") return;
  const dimension = world.getDimension("overworld");

  new ActionFormData()
    .title("§bOneBlock Remote")
    .body("Choose an option:")
    .button("▶ Start / Setup OneBlock")
    .button("♻ Reset OneBlock")
    .button("📊 Show Scoreboard")
    .show(player)
    .then(res => {
      if (res.canceled) return;

      // ▶ Start
      if (res.selection === 0) {
        new ModalFormData()
          .title("OneBlock Setup")
          .textField("Enter X", "0")
          .textField("Enter Y", "100")
          .textField("Enter Z", "0")
          .toggle("Enable Safety Platform", true)
          .dropdown("Select Difficulty", DifficultyNames, 1)
          .show(player)
          .then(r => {
            if (r.canceled) return;
            clearWelcomeTexts();
            clearOldBiomeScoreboard(dimension);

            oneblockData.x = parseInt(r.formValues[0]);
            oneblockData.y = parseInt(r.formValues[1]);
            oneblockData.z = parseInt(r.formValues[2]);
            const useSafety = r.formValues[3];
            oneblockData.difficulty = r.formValues[4];
            oneblockData.phase = 1;
            oneblockData.blockCount = 0;
            oneblockData.active = true;
            oneblockData.upgrading = false;

            dimension.runCommand(`setblock ${oneblockData.x} ${oneblockData.y} ${oneblockData.z} grass_block`);

            if (useSafety) {
              for (let dx = -1; dx <= 1; dx++) {
                for (let dz = -1; dz <= 1; dz++) {
                  try { dimension.runCommand(`setblock ${oneblockData.x + dx} ${oneblockData.y - 1} ${oneblockData.z + dz} glass`); } catch {}
                }
              }
              player.sendMessage("§a🛡 Safety Platform generated!");
            }

            try {
              player.teleport({ x: oneblockData.x + 0.5, y: oneblockData.y + 1, z: oneblockData.z + 0.5 });
              dimension.runCommand(`setworldspawn ${oneblockData.x} ${oneblockData.y + 1} ${oneblockData.z}`);
              player.sendMessage("§a✈ Teleported to OneBlock & World Spawn set!");
            } catch {}

            applyDifficultyRules(dimension);
            player.sendMessage(`§a✅ OneBlock started at Phase 1 - §a${phaseNames[1]}!`);
            player.sendMessage(`§c🔥 Difficulty: ${DifficultyNames[oneblockData.difficulty]}`);

            setBiomeScoreboard(dimension);

            const texts = [
              "§aEnjoy The Game!",
              `§bRunning Biome: ${phaseNames[oneblockData.phase]}`,
              "§dWelcome To Gaming Boy Oneblock",
              "§e⬇ Break This Block ⬇"
            ];
            texts.forEach((txt, i) => {
              try {
                const ent = dimension.spawnEntity("oneblock:floating_text", {
                  x: oneblockData.x + 0.5,
                  y: oneblockData.y + 2.5 + i * 0.5,
                  z: oneblockData.z + 0.5
                });
                ent.nameTag = txt;
                ent.addTag("oneblock_welcome");
                oneblockData.welcomeEntities.push(ent);
              } catch {}
            });

            saveOneblockData();
          });
      }

      // ♻ Reset
      if (res.selection === 1) {
        clearWelcomeTexts();
        clearOldBiomeScoreboard(dimension);
        try { dimension.runCommand("scoreboard players reset * oneblock_count"); } catch {}
        try { dimension.runCommand("kill @e[type=oneblock:floating_text]"); } catch {}
        oneblockData = { x:0,y:0,z:0,phase:1,blockCount:0,active:false,upgrading:false,welcomeEntities:[],currentBiomeScoreboardName:"", difficulty: 1 };
        player.sendMessage("§c♻ OneBlock reset!");
        saveOneblockData();
      }

      // 📊 Show Scoreboard
      if (res.selection === 2) {
        try { dimension.runCommand("scoreboard objectives setdisplay sidebar oneblock_count"); } catch {}
        setBiomeScoreboard(dimension);
        player.sendMessage("§b📊 Scoreboard displayed with biome info!");
      }
    });
});

// ============================
// 🔹 Block break logic
// ============================
world.afterEvents.playerBreakBlock.subscribe(event => {
  if (!oneblockData.active || oneblockData.upgrading) return;
  const { block, dimension, player } = event;
  const loc = block.location;
  if (loc.x === oneblockData.x && loc.y === oneblockData.y && loc.z === oneblockData.z) {
    oneblockData.blockCount++;
    try { dimension.runCommand(`scoreboard players add "${player.name}" oneblock_count 1`); } catch {}

    // next block
    const blocks = phaseBlocks[oneblockData.phase];
    if (blocks?.length) {
      const randomBlock = blocks[Math.floor(Math.random() * blocks.length)];
      try { dimension.runCommand(`setblock ${oneblockData.x} ${oneblockData.y} ${oneblockData.z} ${randomBlock}`); } catch {}
    }

    // mobs
    const mobs = phaseMobs[oneblockData.phase];
    let mobSpawnRate = 0.1;
    // Increase mob spawn rate with difficulty
    if (oneblockData.difficulty >= 2) mobSpawnRate = 0.15;
    if (oneblockData.difficulty >= 3) mobSpawnRate = 0.25;
    if (oneblockData.difficulty >= 4) mobSpawnRate = 0.40;
    if (oneblockData.difficulty >= 5) mobSpawnRate = 0.60;

    if (mobs?.length && Math.random() < mobSpawnRate) {
      const mob = mobs[Math.floor(Math.random() * mobs.length)];
      try { dimension.runCommand(`summon ${mob} ${oneblockData.x} ${oneblockData.y + 1} ${oneblockData.z}`); } catch {}
    }

    // Boss spawn (Super Super Hard+)
    if (oneblockData.difficulty >= 4 && Math.random() < 0.01) {
       const bosses = ["warden", "ravager", "wither_skeleton"];
       const boss = bosses[Math.floor(Math.random() * bosses.length)];
       try { dimension.runCommand(`summon ${boss} ${oneblockData.x} ${oneblockData.y + 1} ${oneblockData.z}`); } catch {}
       player.sendMessage("§c⚠ A Boss has appeared!");
    }

    // loot chest
    if (Math.random() < 0.05) {
      const lootTable = `phase${oneblockData.phase}_chest`;
      try {
        dimension.runCommand(`setblock ${oneblockData.x} ${oneblockData.y + 1} ${oneblockData.z} chest replace`);
        dimension.runCommand(`loot insert ${oneblockData.x} ${oneblockData.y + 1} ${oneblockData.z} loot ${lootTable}`);
        player.sendMessage("§6🎁 A loot chest appeared!");
      } catch {}
    }

    // ✅ Lava/Water bucket fix
    system.runTimeout(() => {
      const blockAt = dimension.getBlock({ 
        x: oneblockData.x, 
        y: oneblockData.y, 
        z: oneblockData.z 
      });
      if (blockAt && (blockAt.typeId === "minecraft:air" || blockAt.typeId === "minecraft:flowing_lava" || blockAt.typeId === "minecraft:flowing_water")) {
        if (blocks?.length) {
          const randomBlock = blocks[Math.floor(Math.random() * blocks.length)];
          try {
            dimension.runCommand(`setblock ${oneblockData.x} ${oneblockData.y} ${oneblockData.z} ${randomBlock}`);
          } catch {}
        }
      }
    }, 5);

    // upgrade
    if (oneblockData.blockCount >= 200) {
      oneblockData.blockCount = 0;
      oneblockData.upgrading = true;
      try { dimension.runCommand(`setblock ${oneblockData.x} ${oneblockData.y} ${oneblockData.z} bedrock`); } catch {}
      let countdown = 60;
      const nextPhase = oneblockData.phase + 1;
      const biomeName = phaseNames[nextPhase] ?? "Unknown";

      const countdownEntity = dimension.spawnEntity("oneblock:floating_text", {
        x: oneblockData.x + 0.5, y: oneblockData.y + 1.5, z: oneblockData.z + 0.5
      });
      countdownEntity.nameTag = `§e⏳ Next: Phase ${nextPhase} - §a${biomeName} §ein ${countdown}s`;

      const upgradeInterval = system.runInterval(() => {
        if (!countdownEntity?.isValid()) { system.clearRun(upgradeInterval); return; }
        countdownEntity.nameTag = `§e⏳ Next: Phase ${nextPhase} - §a${biomeName} §ein ${countdown}s`;
        countdown--;
        if (countdown <= 0) {
          system.clearRun(upgradeInterval);
          if (countdownEntity?.isValid()) countdownEntity.kill();

          oneblockData.phase++;
          oneblockData.upgrading = false;
          updateWelcomeTexts();
          setBiomeScoreboard(dimension);

          // ✅ End Portal from .mcstructure at Phase 15
          if (oneblockData.phase === 15) {
            try {
              dimension.runCommand(`structure load stronghold_end_portal ${oneblockData.x} ${oneblockData.y - 4} ${oneblockData.z}`);
              player.sendMessage("§d✨ A Stronghold End Portal has been generated 4 blocks below!");
            } catch (e) { console.warn("End portal structure load failed:", e); }
          }

          if (oneblockData.phase > 16) {
            player.sendMessage("§b🎉 Congratulations! You completed all phases of OneBlock!");
            oneblockData.active = false;
            clearWelcomeTexts();
            clearOldBiomeScoreboard(dimension);
          } else {
            try { dimension.runCommand(`setblock ${oneblockData.x} ${oneblockData.y} ${oneblockData.z} grass_block`); } catch {}
            for (let i = 0; i < 3; i++) {
              const fx = oneblockData.x + (Math.random() * 2 - 1);
              const fy = oneblockData.y + 1;
              const fz = oneblockData.z + (Math.random() * 2 - 1);
              try { dimension.runCommand(`summon fireworks_rocket ${fx} ${fy} ${fz}`); } catch {}
            }
            player.sendMessage(`§a▶ Phase ${oneblockData.phase} - §a${phaseNames[oneblockData.phase]} §fstarted!`);
          }
          saveOneblockData();
        }
      }, 20);
    }
  }
});

// ============================
// 🔹 Difficulty Logic
// ============================
function applyDifficultyRules(dimension) {
  const diff = oneblockData.difficulty;
  try {
    // Reset defaults
    dimension.runCommand("gamerule naturalregeneration true");
    dimension.runCommand("gamerule keepinventory false");
    dimension.runCommand("gamerule randomtickspeed 1");
    dimension.runCommand("difficulty normal");
  } catch {}

  if (diff === 0) try { dimension.runCommand("difficulty easy"); } catch {}
  if (diff === 1) try { dimension.runCommand("difficulty normal"); } catch {}
  if (diff >= 2) try { dimension.runCommand("difficulty hard"); } catch {}

  // Super Hard+
  if (diff >= 3) try { dimension.runCommand("gamerule naturalregeneration false"); } catch {}
  
  // Extra Ordinary
  if (diff === 5) {
    try { dimension.runCommand("gamerule keepinventory false"); } catch {}
    try { dimension.runCommand("gamerule randomtickspeed 6"); } catch {} // Lava spreads faster
  }
}

function applyDifficultyTick(dimension) {
  const diff = oneblockData.difficulty;
  if (diff < 3) return;

  const players = world.getAllPlayers();
  for (const p of players) {
    if (diff === 3) { // Super Hard
       p.addEffect("hunger", 40, { amplifier: 0, showParticles: false });
    }
    if (diff === 4) { // Super Super Hard
       p.addEffect("hunger", 40, { amplifier: 1, showParticles: false });
       p.addEffect("weakness", 40, { amplifier: 0, showParticles: false });
    }
    if (diff === 5) { // Extra Ordinary
       p.addEffect("hunger", 40, { amplifier: 2, showParticles: false });
       if (Math.random() < 0.05) p.addEffect("darkness", 100, { amplifier: 0, showParticles: true });
    }
  }
  
  // Extra Ordinary Events (Boss mechanics)
  if (diff === 5 && Math.random() < 0.0005) {
     dimension.runCommand(`title @a title §c§lBLOOD MOON`);
     dimension.runCommand(`summon witch ${oneblockData.x + 3} ${oneblockData.y + 1} ${oneblockData.z}`);
     dimension.runCommand(`summon vex ${oneblockData.x - 3} ${oneblockData.y + 1} ${oneblockData.z}`);
  }
}

// 🔹 Mob Buffs & Mechanics
world.afterEvents.entitySpawn.subscribe(ev => {
  if (!oneblockData.active) return;
  const { entity } = ev;
  const diff = oneblockData.difficulty;
  if (diff < 3) return;
  
  // Filter out non-mobs
  if (entity.typeId === "minecraft:player" || entity.typeId === "minecraft:item" || entity.typeId === "oneblock:floating_text") return;

  try {
    // Super Hard
    if (diff >= 3) {
       entity.addEffect("health_boost", 999999, { amplifier: 1, showParticles: false }); // +8 HP
       entity.addEffect("strength", 999999, { amplifier: 0, showParticles: false }); // +3 Dmg
    }
    // Super Super Hard
    if (diff >= 4) {
       entity.addEffect("health_boost", 999999, { amplifier: 4, showParticles: false }); // +20 HP
       entity.addEffect("strength", 999999, { amplifier: 1, showParticles: false }); // +6 Dmg
       entity.addEffect("speed", 999999, { amplifier: 1, showParticles: false });
       
       if (entity.typeId === "minecraft:creeper") {
         entity.runCommand("event entity @s minecraft:start_exploding_forced");
       }
    }
    // Extra Ordinary
    if (diff === 5) {
       entity.addEffect("health_boost", 999999, { amplifier: 9, showParticles: false }); // +40 HP
       entity.addEffect("strength", 999999, { amplifier: 2, showParticles: false }); // +9 Dmg
       entity.addEffect("resistance", 999999, { amplifier: 0, showParticles: false });
    }
    
    // Heal to new max health
    entity.runCommand("effect @s instant_health 1 255 true");
  } catch {}
});

// 🔹 Prevent Sleeping (Super Super Hard+)
world.beforeEvents.playerInteractWithBlock.subscribe(ev => {
  if (!oneblockData.active) return;
  if (oneblockData.difficulty < 4) return;
  if (ev.block.typeId.includes("bed")) {
    ev.cancel = true;
    ev.player.sendMessage("§c😴 Sleeping is disabled in this difficulty!");
  }
});