import { EntityComponentTypes, ItemStack, system, world } from "@minecraft/server";
import { lavaSpongePlace } from "./handlers/lava_sponges";
import { posionSponge } from "./handlers/poison_sponge";
import { nightVisionPulse } from "./handlers/night_vision_sponge";
import { feedingSpongePulse } from "./handlers/feeding_sponge";
import { fireSpongePlace } from "./handlers/fire_sponge";
import { explosionSponge, explosionSpongeTick, removeExplosionSpongeBlock } from "./handlers/explosion_sponge";
import { voidSpongePulse } from "./handlers/void_sponge";
import { growthSpongePulse } from "./handlers/growth_sponge";
import { lightSpongePulse } from "./handlers/light_sponge";
import { breakXpSponge, getXPSponge, xpSpongePulse } from "./handlers/xp_sponge";
import { healingSpongePulse } from "./handlers/healing_sponge";
import { redstoneSponge } from "./handlers/redstone_sponge";
import { frostSpongePulse } from "./handlers/frost_sponge";
import { removeTntSponge, tntSpongePulse } from "./handlers/tnt_sponge";
import { speedSpongePulse } from "./handlers/speed_sponge";
import { gravitySpongePulse } from "./handlers/gravity_sponge";
import { nightSpongePlace, nightSpongeRemove } from "./handlers/night_sponge";
import { teleportSponge } from "./handlers/teleport_sponge";
import { decaySpongePulse } from "./handlers/decay_sponge";
import { witherSpongePulse } from "./handlers/wither_sponge";
import { antiEnderSpongePulse } from "./handlers/anti-ender_sponge";
import { magnetSpongePulse } from "./handlers/magnet_sponge";
import { silkSpongePulse } from "./handlers/silk_sponge";
import { smokeSpongePlace, smokeSpongePulse } from "./handlers/smoke_sponge";
import { stickySpongePlace, stickySpongeAreaCheck, stickySpongeRemove, stickySpongeOnPlace } from "./handlers/sticky_sponge";
import { jumpSpongePulse } from "./handlers/jump_sponge";
import { clearWeatherSpongePlace } from "./handlers/clear_weather_sponge";
import { shadowSpongePulse } from "./handlers/shadow_sponge";
import { removeSilkSponge } from "./handlers/silk_sponge";
import { thornSpongePulse } from "./handlers/thorn_sponge";
import { effectsSpongePulse } from "./handlers/effects_sponge";
import { openSettingsMenuMain } from "./forms/settingsMenu";
import { openStarterBookMain } from "./forms/starterBook";
// Block placement
world.afterEvents.playerPlaceBlock.subscribe(({ block, player }) => {
    switch (block.typeId) {
        case "wildphire_spg:lava_sponge_empty":
            lavaSpongePlace(player, block);
            break;
        case "wildphire_spg:poison_sponge":
            posionSponge(player, block);
            break;
        case "wildphire_spg:fire_sponge":
            fireSpongePlace(block);
            break;
        case "wildphire_spg:sticky_sponge":
            stickySpongePlace(player, block);
            break;
        case "wildphire_spg:night_sponge":
            nightSpongePlace(block, player);
            break;
        case "wildphire_spg:clear_weather_sponge":
            clearWeatherSpongePlace(block, player);
            break;
    }
});
world.beforeEvents.playerInteractWithBlock.subscribe((event) => {
    const blockType = event.block.typeId;
    if (blockType == "wildphire_spg:xp_sponge") {
        const xpSpongeData = getXPSponge(event.block);
        // Do something with xpSpongeData
        system.run(() => {
            event.player.onScreenDisplay.setActionBar(`§aTotal XP Stored: §b${xpSpongeData}§r`);
        });
    }
});
// Component Registration
world.beforeEvents.worldInitialize.subscribe(({ blockComponentRegistry, itemComponentRegistry }) => {
    const register = (id, { onTick, onPlace }) => {
        blockComponentRegistry.registerCustomComponent(id, {
            ...(onTick && { onTick: e => onTick(e.block) }),
            ...(onPlace && { onPlace: e => onPlace(e.block) })
        });
    };
    const itemRegister = (id, { onUse }) => {
        itemComponentRegistry.registerCustomComponent(id, {
            onUse: e => onUse(e.source)
        });
    };
    register("wildphire_spg:night_vision_sponge", { onTick: nightVisionPulse, onPlace: nightVisionPulse });
    register("wildphire_spg:explosion_sponge", { onTick: explosionSpongeTick });
    register("wildphire_spg:void_sponge", { onTick: voidSpongePulse });
    register("wildphire_spg:growth_sponge", { onTick: growthSpongePulse });
    register("wildphire_spg:light_sponge", { onTick: lightSpongePulse });
    register("wildphire_spg:xp_sponge", { onTick: xpSpongePulse });
    register("wildphire_spg:healing_sponge", { onTick: healingSpongePulse, onPlace: healingSpongePulse });
    register("wildphire_spg:speed_sponge", { onTick: speedSpongePulse, onPlace: speedSpongePulse });
    register("wildphire_spg:gravity_sponge", { onTick: gravitySpongePulse, onPlace: gravitySpongePulse });
    register("wildphire_spg:redstone_sponge", { onPlace: redstoneSponge });
    register("wildphire_spg:frost_sponge", { onPlace: frostSpongePulse });
    register("wildphire_spg:teleport_sponge", { onTick: teleportSponge, onPlace: teleportSponge });
    register("wildphire_spg:tnt_sponge", { onTick: tntSpongePulse });
    register("wildphire_spg:decay_sponge", { onTick: decaySpongePulse });
    register("wildphire_spg:wither_sponge", { onTick: witherSpongePulse, onPlace: witherSpongePulse });
    register("wildphire_spg:anti_ender_sponge", { onTick: antiEnderSpongePulse, onPlace: antiEnderSpongePulse });
    register("wildphire_spg:magnet_sponge", { onTick: magnetSpongePulse, onPlace: magnetSpongePulse });
    register("wildphire_spg:silk_sponge", { onTick: silkSpongePulse, onPlace: silkSpongePulse });
    register("wildphire_spg:smoke_sponge", { onTick: smokeSpongePulse, onPlace: smokeSpongePlace });
    register("wildphire_spg:sticky_sponge", { onTick: stickySpongeAreaCheck, onPlace: stickySpongeOnPlace });
    register("wildphire_spg:night_sponge", { onPlace: nightSpongePlace });
    register("wildphire_spg:feeding_sponge", { onTick: feedingSpongePulse, onPlace: feedingSpongePulse });
    register("wildphire_spg:jump_sponge", { onTick: jumpSpongePulse, onPlace: jumpSpongePulse });
    register("wildphire_spg:thorn_sponge", { onTick: thornSpongePulse });
    register("wildphire_spg:effects_sponge", { onTick: effectsSpongePulse, onPlace: effectsSpongePulse });
    register("wildphire_spg:shadow_sponge", { onTick: shadowSpongePulse, onPlace: shadowSpongePulse });
    itemRegister("wildphire_spg:starter_book", {
        onUse: (player) => {
            if (player.isSneaking)
                openSettingsMenuMain(player);
            else
                openStarterBookMain(player);
        }
    });
});
// Block breaking
world.beforeEvents.playerBreakBlock.subscribe((event) => {
    const block = event.block;
    const player = event.player;
    const dimension = block.dimension;
    const denyBreak = (msg = true) => {
        if (msg)
            sendActionbarMessage(player, "§cYou cannot break this block!§r\n§7Please wait for it to finish.");
        event.cancel = true;
    };
    switch (block.typeId) {
        case "wildphire_spg:poison_sponge":
        case "wildphire_spg:fire_sponge":
        case "wildphire_spg:redstone_sponge":
        case "wildphire_spg:frost_sponge":
        case "wildphire_spg:clear_weather_sponge":
        case "wildphire_spg:wither_sponge":
            event.cancel = true;
            denyBreak();
            break;
        case "wildphire_spg:explosion_sponge":
            event.cancel = true;
            removeExplosionSpongeBlock(block.location, dimension);
            break;
        case "wildphire_spg:xp_sponge":
            breakXpSponge(block, player);
            break;
        case "wildphire_spg:tnt_sponge":
            if (!removeTntSponge(block))
                denyBreak(false);
            break;
        case "wildphire_spg:silk_sponge":
            removeSilkSponge(block.location);
            break;
        case "wildphire_spg:sticky_sponge":
            stickySpongeRemove(block.location, dimension);
            break;
        case "wildphire_spg:night_sponge":
            nightSpongeRemove(block);
            break;
    }
});
// Helper
function sendActionbarMessage(player, message) {
    system.run(() => player.onScreenDisplay.setActionBar(message));
}
// Helper function to give item to player or drop it
function giveOrDropItem(player, item) {
    try {
        // First, try to add to inventory
        const inventoryComponent = player.getComponent(EntityComponentTypes.Inventory);
        if (inventoryComponent && inventoryComponent.container) {
            const addedItem = inventoryComponent.container.addItem(item);
            // If addItem returns undefined, the item was successfully added
            if (addedItem === undefined) {
                return; // Successfully added to inventory
            }
        }
        // If we reach here, inventory is full or couldn't add - drop the item
        player.dimension.spawnItem(item, player.location);
    }
    catch (error) {
        // Fallback: drop the item if anything goes wrong
        try {
            player.dimension.spawnItem(item, player.location);
        }
        catch {
            // Silent fail if even dropping fails
        }
    }
}
// Explosion event
world.beforeEvents.explosion.subscribe((event) => {
    try {
        const sourceLoc = event.source?.location || event.getImpactedBlocks()[0]?.location;
        if (sourceLoc) {
            event.cancel = explosionSponge(sourceLoc, event.dimension);
        }
    }
    catch { }
});
system.runInterval(() => {
    const players = world.getPlayers();
    for (const player of players) {
        if (!player.hasTag("wildphire_spg:starter_guide")) {
            const item = new ItemStack("wildphire_spg:starter_book", 1);
            giveOrDropItem(player, item);
            player.addTag("wildphire_spg:starter_guide");
        }
    }
}, 20);
