import { world, system, Player } from "@minecraft/server";
import { ActionFormData, ModalFormData, MessageFormData } from "@minecraft/server-ui";
import { cachedPlayers } from './lag/pvp.js';
import { getOwner } from './custom/custom6.js';
import { getPlotIdAtLocation } from './gui/index.js';

const protectedRegions = [
  {
    min: { x: 3943, y: 5, z: -4054 }, // mining sim auto gen areas
    max: { x: 3945, y: 11, z: -4056 }
  },
  {
    min: { x: 3943, y: 5, z: -4064 }, // mining sim auto gen areas
    max: { x: 3945, y: 11, z: -4062 }
  },
  {
    min: { x: 3943, y: 5, z: -4072 }, // mining sim auto gen areas
    max: { x: 3945, y: 11, z: -4070 }
  },
  {
    min: { x: 3943, y: 5, z: -4078 }, // mining sim auto gen areas
    max: { x: 3945, y: 11, z: -4080 }
  },
  {
    min: { x: 3933, y: 5, z: -4078 }, // mining sim auto gen areas
    max: { x: 3935, y: 11, z: -4080 }
  },
  {
    min: { x: 3933, y: 5, z: -4072 }, // mining sim auto gen areas
    max: { x: 3935, y: 11, z: -4070 }
  },
  {
    min: { x: 3933, y: 5, z: -4064 }, // mining sim auto gen areas
    max: { x: 3935, y: 11, z: -4062 }
  },
  {
    min: { x: 3933, y: 5, z: -4056 }, // mining sim auto gen areas
    max: { x: 3935, y: 11, z: -4054 }
  },
  {
    min: { x: 3929, y: 5, z: -4048 }, // mining sim auto gen areas
    max: { x: 3931, y: 11, z: -4046 }
  },
  {
    min: { x: 3957, y: 5, z: -4048 }, // mining sim auto gen areas
    max: { x: 3959, y: 11, z: -4046 }
  },
  {
    min: { x: 3953, y: 5, z: -4056 }, // mining sim auto gen areas
    max: { x: 3955, y: 11, z: -4054 }
  },
  {
    min: { x: 3953, y: 5, z: -4064 }, // mining sim auto gen areas
    max: { x: 3955, y: 11, z: -4062 }
  },
  {
    min: { x: 3953, y: 5, z: -4070 }, // mining sim auto gen areas
    max: { x: 3955, y: 11, z: -4072 }
  },
  {
    min: { x: 3953, y: 5, z: -4078 }, // mining sim auto gen areas
    max: { x: 3955, y: 11, z: -4080 }
  },
  {
    min: { x: 3003, y: 6, z: 3001 }, // Admin shop
    max: { x: 3004, y: 10, z: 3001 }
  },
  {
    min: { x: -3971, y: 12, z: -3891 }, // vip Island 
    max: { x: -3985, y: 15, z: -3877 }
  },
  {
    min: { x: -3971, y: 17, z: -3891 }, // vip Island 
    max: { x: -3972, y: 22, z: -3877 }
  },
  {
    min: { x: -3973, y: 17, z: -3891 }, // vip Island 
    max: { x: -3985, y: 22, z: -3890 }
  },
  {
    min: { x: -3985, y: 17, z: -3889 }, // vip Island 
    max: { x: -3984, y: 22, z: -3877 }
  },
  {
    min: { x: -3983, y: 17, z: -3877 }, // vip Island 
    max: { x: -3973, y: 20, z: -3878 }
  },
  {
    min: { x: -3983, y: 19, z: -3889 }, // vip Island 
    max: { x: -3973, y: 22, z: -3879 }
  },
  {
    min: { x: 2977, y: 47, z: -3037 },
    max: { x: 2993, y: 26, z: -3083 }
  },
  {
    min: { x: 3023, y: 47, z: -3026 },
    max: { x: 3019, y: 26, z: -3074 }
  },
  {
    min: { x: 2977, y: 47, z: -2982 },
    max: { x: 2990, y: 26, z: -2917 }
  },
  {
    min: { x: 3959, y: 4, z: -4015 },
    max: { x: 3929, y: 11, z: -3985 }
  },
  {
    min: { x: 2976, y: 4, z: -2988 },
    max: { x: 2994, y: 12, z: -2916 }
  },
  {
    min: { x: 3024, y: 4, z: -2925 },
    max: { x: 3006, y: 12, z: -2979 }
  },
  {
    min: { x: 2976, y: 4, z: -3012 },
    max: { x: 2994, y: 12, z: -3084 }
  },
  {
    min: { x: 3006, y: 4, z: -3075 },
    max: { x: 3024, y: 12, z: -3021 }
  }
];




const overworld = world.getDimension("overworld");

// === CONFIG ===
const ZONE_CENTER = { x: 5000, y: 60, z: 5000 };
const ZONE_RADIUS = 116;
const REGEN_TIME = 200; // 5s (20tps * 5)

// === HELPERS ===
function isInZone(loc) {
  const dx = loc.x - ZONE_CENTER.x;
  const dy = loc.y - ZONE_CENTER.y;
  const dz = loc.z - ZONE_CENTER.z;
  return (dx * dx + dy * dy + dz * dz) <= (ZONE_RADIUS * ZONE_RADIUS);
}

// === SPECIAL CASE: Redstone ore absorption ===
world.afterEvents.playerBreakBlock.subscribe(event => {
  const { block, player, brokenBlockPermutation } = event;
  if (!block || !isInZone(block.location)) return;

  const brokenId = brokenBlockPermutation?.type?.id;
  if (brokenId !== "minecraft:redstone_ore" && brokenId !== "minecraft:lit_redstone_ore") return;

  // Apply Health Boost instead of Absorption
const effect = player.getEffect("absorption");
const newAmplifier = effect ? Math.min(effect.amplifier + 1, 4) : 0; // max 5 extra hearts (level 4)
player.addEffect("absorption", 600, { amplifier: newAmplifier, showParticles: false });
player.playSound("block.end_portal_frame.fill", { location: player.location, volume: 1, pitch: 1 });

  // Immediately replace with bedrock (no waiting)
  const minedBlock = overworld.getBlock(block.location);
  if (minedBlock && (minedBlock.typeId === "minecraft:redstone_ore" || minedBlock.typeId === "minecraft:lit_redstone_ore" || minedBlock.typeId === "minecraft:air")) {
    minedBlock.setType("minecraft:bedrock");
  }

  // Schedule regen
  system.runTimeout(() => {
    const regenBlock = overworld.getBlock(block.location);
    if (regenBlock && regenBlock.typeId === "minecraft:bedrock") {
      regenBlock.setType("minecraft:redstone_ore");
    }
  }, REGEN_TIME);
});

// === ANDESITE PLACEMENT AUTO-DESPAWN ===
world.afterEvents.playerPlaceBlock.subscribe(event => {
  const { block } = event;
  if (!block || !isInZone(block.location)) return;

  if (block.typeId === "minecraft:andesite") {
    // Remove immediately if block exists outside zone or weird duplicates
    const removeAndesite = () => {
      const checkBlock = overworld.getBlock(block.location);
      if (checkBlock?.typeId === "minecraft:andesite") {
        checkBlock.setType("minecraft:air");
      }
    };

    system.runTimeout(removeAndesite, REGEN_TIME);
  }
});



world.beforeEvents.playerBreakBlock.subscribe(event => {
  const { block, player } = event;
  if (!block || !player) return;


if (player.hasTag("gwim:Admin")) return; // Admin bypass for main zone
  // Check if inside a plot
const plotId = getPlotIdAtLocation(block.location);
if (plotId) {
    const owner = getOwner(plotId);

    if (player.name === owner) return; // Owner bypass

    // Non-owner blocked
    if (owner) {
        player.sendMessage(`§cPlot §b#${plotId} §cbelongs to §e${owner}§c! You can’t break blocks here.`);
    } else {
        player.sendMessage(`§cPlot §b#${plotId} §cis §eunowned§c! Buy it first before building.`);
    }

    player.runCommandAsync("playsound note.bass @s");
    event.cancel = true;
    return;
}

  // ===========================
  // Existing code below remains unchanged
  // ===========================

  // extra restricted region check (always applies, even outside main zone)
  const inRestrictedRegion =
    block.location.x >= -3985 && block.location.x <= -3971 &&
    block.location.y >= 17    && block.location.y <= 18 &&
    block.location.z >= -3891 && block.location.z <= -3877;

  // prevent breaking ONLY these blocks inside the restricted region
  if (
    inRestrictedRegion &&
    (block.typeId === "minecraft:polished_tuff" ||
     block.typeId === "minecraft:tuff_brick_stairs" ||
     block.typeId === "minecraft:spruce_leaves")
  ) {
    if (!player.hasTag("gwim:Admin")) {
      event.cancel = true;
      return;
    }
  }

  // now check the main zone
  if (!isInZone(block.location)) return;


  const allowed = [
    "minecraft:redstone_ore",
    "minecraft:lit_redstone_ore",
    "minecraft:andesite"
  ];

  if (!allowed.includes(block.typeId)) event.cancel = true;
});



//vip button


function removeItems(player, typeId, amount) {
    const inventory = player.getComponent("minecraft:inventory").container;
    for (let slot = 0; slot < inventory.size; slot++) {
        const item = inventory.getItem(slot);
        if (!item || item.typeId !== typeId) continue;

        if (item.amount <= amount) {
            amount -= item.amount;
            inventory.setItem(slot, undefined);
        } else {
            const reducedItem = item.clone();
            reducedItem.amount = item.amount - amount;
            inventory.setItem(slot, reducedItem);
            amount = 0;
        }

        if (amount <= 0) break;
    }
}

export function showBlockMenu(player) {
    const inventory = player.getComponent("minecraft:inventory").container;
    const moneyObjective = world.scoreboard.getObjective("Money");

    const BLOCKS = [
        { type: "minecraft:coal_block", name: "Coal Block", displayName: "§l§8Coal Block", price: 400 },
        { type: "minecraft:lapis_block", name: "Lapis Block", displayName: "§l§9Lapis Block", price: 150 },
        { type: "minecraft:iron_block", name: "Iron Block", displayName: "§l§fIron Block", price: 700 },
        { type: "minecraft:copper_block", name: "Copper Block", displayName: "§l§6Copper Block", price: 600 },
        { type: "minecraft:gold_block", name: "Gold Block", displayName: "§l§eGold Block", price: 800 },
        { type: "minecraft:diamond_block", name: "Diamond Block", displayName: "§l§bDiamond Block", price: 1000 },
        { type: "minecraft:emerald_block", name: "Emerald Block", displayName: "§l§aEmerald Block", price: 900 },
        { type: "minecraft:redstone_block", name: "Redstone Block", displayName: "§l§cRedstone Block", price: 300 },
        { type: "minecraft:quartz_block", name: "Quartz Block", displayName: "§l§fQuartz Block", price: 250 },
        { type: "minecraft:netherite_block", name: "Netherite Block", displayName: "§l§7Netherite Block", price: 8000 }
    ];

    const inventoryCounts = {};
    let totalSellable = 0;
    for (let slot = 0; slot < inventory.size; slot++) {
        const item = inventory.getItem(slot);
        if (!item) continue;
        inventoryCounts[item.typeId] = (inventoryCounts[item.typeId] || 0) + item.amount;
    }
    for (const block of BLOCKS) {
        totalSellable += inventoryCounts[block.type] ?? 0;
    }

    if (totalSellable === 0) {
        player.sendMessage("§cYou don't have any sellable blocks.");
        player.playSound("note.bass");
        return;
    }

   
    const form = new ModalFormData()
        .title("§lVIP Minerals Sell")
        .dropdown("§7Select a mode", [
            "§aManual Sell (Use sliders)",
            `§cSell All (${totalSellable})`
        ]);
        
    const priceInfo = BLOCKS.map(b => `§7- ${b.displayName} §f= §a$${b.price}`).join("\n");
    
    form.slider(
        `§l§6Welcome to VIP Minerals Sell!\n§r§fUse the sliders below to sell specific amounts,\nor choose §c"Sell All"§f above to sell everything.\n\n§l§eSellable Blocks:\n${priceInfo}`,
        0, 0, 0, 0
    );

    for (const block of BLOCKS) {
        const count = inventoryCounts[block.type] ?? 0;
        form.slider(`${block.displayName} §7(0–${count})`, 0, count, 1, 0);
    }

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

        const selectedMode = res.formValues[0];
        const sliderValues = res.formValues.slice(2);

        if (selectedMode === 1) {
            // SELL ALL MODE
            let totalAmount = 0;
            let totalMoney = 0;
            let summaryLines = [];

            for (const block of BLOCKS) {
                const count = inventoryCounts[block.type] ?? 0;
                if (count > 0) {
                    const earn = count * block.price;
                    totalAmount += count;
                    totalMoney += earn;
                    summaryLines.push(`${block.displayName} §rx §e${count} §7= §a$${earn}§r`);
                }
            }

            const confirm = new MessageFormData()
                .title("§lConfirm Sell All")
                .body(`You're selling:\n\n${summaryLines.join("\n")}\n\n§l§fTotal: §a§l$${totalMoney}§r`)
                .button1("§cCancel")
                .button2("§aConfirm");

            confirm.show(player).then(confirmRes => {
                if (confirmRes.selection !== 1) {
                    player.sendMessage("§cSell cancelled.");
                    player.playSound("note.bass");
                    return;
                }

                for (const block of BLOCKS) {
                    const count = inventoryCounts[block.type] ?? 0;
                    if (count > 0) removeItems(player, block.type, count);
                }

                if (moneyObjective) {
                    const current = moneyObjective.getScore(player) ?? 0;
                    moneyObjective.setScore(player, current + totalMoney);
                }

                player.sendMessage(`§gYou sold ${totalAmount} blocks for §a$${totalMoney}`);
                player.playSound("random.orb");
            });

        } else {
            // MANUAL SLIDER MODE
            let totalAmount = 0;
            let totalMoney = 0;
            let summaryLines = [];

            for (let i = 0; i < sliderValues.length; i++) {
                const amount = sliderValues[i];
                const block = BLOCKS[i];
                if (amount > 0) {
                    const earn = amount * block.price;
                    totalAmount += amount;
                    totalMoney += earn;
                    summaryLines.push(`${block.displayName} §rx §e${amount} §7= §a$${earn}§r`);
                }
            }

            if (totalAmount === 0) {
                player.sendMessage("§cNothing selected to sell!");
                player.playSound("note.bass");
                return;
            }

            const confirm = new MessageFormData()
                .title("§lConfirm Sale")
                .body(`You're selling:\n\n${summaryLines.join("\n")}\n\n§l§fTotal: §a§l$${totalMoney}§r`)
                .button1("§cCancel")
                .button2("§aConfirm");

            confirm.show(player).then(confirmRes => {
                if (confirmRes.selection !== 1) {
                    player.sendMessage("§cSell cancelled.");
                    player.playSound("note.bass");
                    return;
                }

                for (let i = 0; i < sliderValues.length; i++) {
                    const amountToRemove = sliderValues[i];
                    if (amountToRemove > 0) {
                        removeItems(player, BLOCKS[i].type, amountToRemove);
                    }
                }

                if (moneyObjective) {
                    const current = moneyObjective.getScore(player) ?? 0;
                    moneyObjective.setScore(player, current + totalMoney);
                }

                player.sendMessage(`§gYou sold ${totalAmount} blocks for §a$${totalMoney}`);
                player.playSound("random.orb");
            });
        }
    });
}

