import { world, system, ItemStack, BlockPermutation } from "@minecraft/server";
import { Vector } from './vector.js';
import { ActionFormData } from "@minecraft/server-ui";

//console.warn("Console loaded");


import * as JSspell_altar from './spell_altar.js';
import * as JSarkane_forge from './arkane_forge.js';
import * as JSbroomstick from './broomstick.js';
import * as JSabilities from './abilities.js';
import * as JSfountain from './upgrade_fountain.js';



system.afterEvents.scriptEventReceive.subscribe((data) => {
    const { id, sourceEntity, message } = data;

    if (id === "mf_mg:give_weapon") {
        if (sourceEntity.typeId !== "minecraft:player") return;
        const parts = message.split(" ")
        if (parts.length < 4) {
            sourceEntity.sendMessage("§cWrong format : scriptevent mf_mg:give_weapon <weapon> <element> <rarity> <abilities>")
            return;
        }
        const weapon = parts[0]
        const element = parts[1]
        const rarity = parts[2]
        const ability = JSON.parse(parts[3] + " " + (parts.length > 4 ? parts[4] : ""))


        const ABILITIES = [
            "Balling", "Tornado", "Shield", "Geyser", "Afterlife", "Fury", "Power Ring", "Rifle", "Blaster", "Lifesteal", "Wings", "Wall", "Lumus"
        ]

        const item = new ItemStack(`mf_mg:${weapon}_${element}_${rarity}${weapon == "tome" ? `_4` : ""}`, 1)
        let newLore = ["§l§eAbility:"]
        if (ability.length > 1) {
            ability.forEach(a => {
                //  console.warn(a)
                if (ABILITIES.includes(a))
                    newLore.push(`-§d§l${a}§r`)
            })
        }

        item.setLore(newLore)
        const droppedItem = sourceEntity.dimension.spawnItem(item, sourceEntity.location)

    }


    if (id === 'mf_mg:guidebook_use') {
        if (!sourceEntity) return
        const MAX_PAGE = 48

        const player = sourceEntity.dimension.getEntities({ type: "minecraft:player", location: sourceEntity.location, maxDistance: 10 })[0]

        if (player.isSneaking) {
            sourceEntity.setProperty("mf_mg:is_removed", true)
            system.runTimeout(() => {
                player.dimension.spawnItem(new ItemStack("mf_mg:guidebook_spawn_egg", 1), sourceEntity.location);
                sourceEntity.dimension.playSound("random.pop", sourceEntity.location)
                sourceEntity.remove()
            }, 22)
            return
        }

        const prop = "mf_mg:guidebook_page"
        const page = sourceEntity.getProperty(prop)
        if (page > 47) {
            sourceEntity.setProperty("mf_mg:is_removed", true)
            system.runTimeout(() => {
                player.dimension.spawnItem(new ItemStack("mf_mg:guidebook_spawn_egg", 1), sourceEntity.location);
                sourceEntity.dimension.playSound("random.pop", sourceEntity.location)
                sourceEntity.remove()
            }, 22)
        }
        if (page < MAX_PAGE) {
            sourceEntity.setProperty(prop, page + 1)
            system.runTimeout(() => {
                sourceEntity.setProperty("mf_mg:page_display", page + 1)
            }, 10)
        }
    }

    if (id === 'mf_mg:guidebook_punch') {
        if (!sourceEntity) return

        const player = sourceEntity.dimension.getEntities({ type: "minecraft:player", location: sourceEntity.location, maxDistance: 10 })[0]

        const prop = "mf_mg:guidebook_page"
        const page = sourceEntity.getProperty(prop)
        if (page > -1) {
            sourceEntity.setProperty(prop, page - 1)
            system.runTimeout(() => {
                sourceEntity.setProperty("mf_mg:page_display", page - 1)
            }, 10)
        }
        if (page == 0) {
            sourceEntity.setProperty("mf_mg:is_removed", true)
            system.runTimeout(() => {
                player.dimension.spawnItem(new ItemStack("mf_mg:guidebook_spawn_egg", 1), sourceEntity.location);
                sourceEntity.dimension.playSound("random.pop", sourceEntity.location)
                sourceEntity.remove()
            }, 22)
        }
    }

});






world.afterEvents.playerSpawn.subscribe((e) => {
    const { initialSpawn, player } = e;

    if (!player.hasTag("mf_mg.has_guidebook")) {
        player.dimension.spawnItem(new ItemStack("mf_mg:guidebook_spawn_egg", 1), player.location);
        system.runTimeout(() => {
            try {
                player.runCommand(`tellraw @s {"rawtext":[{"text":"§dMagic Add-On§r installed!"}]}`)
            } catch { }
        }, 40)
        player.addTag("mf_mg.has_guidebook");
    }

})


world.afterEvents.playerSpawn.subscribe((e) => {
    const { initialSpawn, player } = e;
    if (!initialSpawn) return
    if (player.dimension.id !== "minecraft:overworld") return

    const nearbyTraders = player.dimension.getEntities({
        type: "mf_mg:trader",
        location: player.location,
        maxDistance: 100,
    });

    if (nearbyTraders.length > 0) return;

    const center = player.location;
    const radius = 25;
    const minDistance = 15;

    function findValidBlock(center, radius, minDistance) {
        const blocksToCheck = [];

        for (let dx = -radius; dx <= radius; dx++) {
            for (let dz = -radius; dz <= radius; dz++) {
                for (let dy = -radius; dy <= radius; dy++) {
                    const distance = Math.sqrt(dx * dx + dy * dy + dz * dz);
                    if (distance >= minDistance && distance <= radius) {
                        const pos = {
                            x: Math.floor(center.x + dx),
                            y: Math.floor(center.y + dy),
                            z: Math.floor(center.z + dz),
                        };
                        blocksToCheck.push(pos);
                    }
                }
            }
        }

        for (const pos of blocksToCheck) {
            const block = player.dimension.getBlock(pos);
            const blockBelow = player.dimension.getBlock({
                x: pos.x,
                y: pos.y - 1,
                z: pos.z,
            });

            if (block?.isAir && !blockBelow?.isAir && !blockBelow?.typeId.includes("water") && !blockBelow?.typeId.includes("lava")) {
                return block;
            }
        }

        return null;
    }

    const validBlock = findValidBlock(center, radius, minDistance);

    if (validBlock) {
        const trader = player.dimension.spawnEntity("mf_mg:trader", validBlock.location);
        // console.warn('spawned Trader at ' + validBlock.location.x, validBlock.location.y, validBlock.location.z)
    }
});




