//main.js
import * as mc from "@minecraft/server";
import { Entity } from "utils/entity";
import { Item } from "utils/item";
import { WikiEntry, WikiMenu } from "./utils/book";
import { ArmorPiece, ArmorSet } from "utils/armor";
import { ActionFormData } from "@minecraft/server-ui";

const GUIDE_BOOK_ITEM_ID = 'cc_aql:guide_book';

mc.world.afterEvents.playerSpawn.subscribe((e ) => {
    try {
      if (e.initialSpawn && !e.player.hasTag("aql_added")) {
        const p = e.player;
        p.runCommand('loot spawn ~ ~ ~ loot "cc/aql/guide_book"');
        e.player.addTag("aql_added");
      } else return;
    } catch (eeerr) {
    }
});

// Crear las piezas de armadura y sus sets
const scubaMask = new ArmorPiece("cc_aql:scuba_mask", "Head", [
    { name: "night_vision", amplifier: 2, duration: 3 }
]);
const scubaTank = new ArmorPiece("cc_aql:scuba_tank", "Chest", [
    { name: "water_breathing", amplifier: 2, duration: 3 }
]);
const scubaLeggings = new ArmorPiece("cc_aql:scuba_leggings", "Legs");
const scubaFins = new ArmorPiece("cc_aql:scuba_fins", "Feet");
const scubaSet = new ArmorSet("scuba_set", [scubaMask, scubaTank, scubaLeggings, scubaFins], [
], 0.04);

const divingHelmet = new ArmorPiece("cc_aql:diving_helmet", "Head", []);
const divingChestplate = new ArmorPiece("cc_aql:diving_chestplate", "Chest", []);
const divingPants = new ArmorPiece("cc_aql:diving_pants", "Legs", []);
const divingBoots = new ArmorPiece("cc_aql:diving_boots", "Feet", []);

const divingSet = new ArmorSet("diving_set", [divingHelmet, divingChestplate, divingPants, divingBoots], [
    { name: "resistance", amplifier: 1, duration: 5 },
    { name: "strength", amplifier: 0, duration: 5 },
    { name: "water_breathing", amplifier: 0, duration: 5 }
], 0.01);


// Lista de sets
let armorSets = [scubaSet, divingSet];

// Intervalo para aplicar efectos (cada tick)
mc.system.runInterval(() => {
    for (const player of mc.world.getAllPlayers()) {
        try {
            if (!player.isInWater) return;

            let setEquipped = false;
            armorSets.forEach(armorSet => {
                armorSet.pieces.forEach(piece => {
                    const equipment = player.getComponent("minecraft:equippable");
                    if (!equipment) return;

                    const equippedPiece = equipment.getEquipment(piece.slot);
                    if (equippedPiece?.typeId === piece.typeId) {
                        piece.applyEffects(player);
                    }
                });


                if (armorSet.isFullSetEquipped(player)) {
                    setEquipped = true;
                    armorSet.applySetEffects(player);
                }
            });


            if (!setEquipped) {
                const movement = player.getComponent("minecraft:underwater_movement");
                movement.resetToDefaultValue();
            }

        } catch (e) {
        }
    }
}, 1);

// Intervalo
mc.system.runInterval(() => {
    for (const player of mc.world.getAllPlayers()) {
        try {
            armorSets.forEach(armorSet => {
                armorSet.pieces.forEach(piece => {
                    const equipment = player.getComponent("equippable");
                    const equippedPiece = equipment.getEquipmentSlot(piece.slot);

                    // Aplicar durabilidad solo si el jugador lleva una pieza de armadura de este set
                    if (equippedPiece?.typeId === piece.typeId && player.isInWater) {
                        Item.durability(player, equippedPiece.getItem(), piece.slot);
                    }
                });
            });
        } catch (e) {
        }
    }
}, 200); // 200 ticks = 10 segundos

mc.world.afterEvents.playerBreakBlock.subscribe(e => {
    try {
        Entity.summonWhenBreakBlock(data, 50, "minecraft:dirt", "cc_aql:worm");


        if (e.player.getComponent("equippable")?.getEquipmentSlot(mc.EquipmentSlot.Mainhand).typeId === 'cc_aql:shark_tooth_sword') {
            Item.durability(e.player, e.player.getComponent("equippable")?.getEquipmentSlot(mc.EquipmentSlot.Mainhand).getItem(), mc.EquipmentSlot.Mainhand);
        }
    } catch (e) {

    }

});
mc.world.afterEvents.entityHitEntity.subscribe((e) => {
    try {
        let _target = e.hitEntity;
        let _armedAttacked = e.damagingEntity.getComponent(mc.EntityComponentTypes.Equippable);
        let _attackerItem = _armedAttacked?.getEquipment(mc.EquipmentSlot.Mainhand);
        if (_attackerItem.typeId === 'cc_aql:shark_tooth_sword') {
            /*if(_target.getComponent('minecraft:type_family').hasTypeFamily('undead')) {
                _target.applyDamage(4, { cause: mc.EntityDamageCause.entityAttack});
            }*/
            for (let i = 0; i < _target.getComponent('minecraft:type_family').getTypeFamilies().length; i++) {
                switch (_target.getComponent('minecraft:type_family').getTypeFamilies()[i]) {
                    case 'undead':
                        _target.applyDamage(15, { cause: mc.EntityDamageCause.entityAttack });
                        break;
                    case 'cc_aql_shark':
                        _target.applyDamage(8, { cause: mc.EntityDamageCause.entityAttack });
                        break;
                    case 'cc_aql_orca':
                        _target.applyDamage(13, { cause: mc.EntityDamageCause.entityAttack });
                        break;
                }
            }
        }
    } catch (e) {

    }

});


const diamondSword = new WikiEntry(
    "Diamond Sword", "A powerful weapon made of diamond.", "textures/ui/diamond_sword.png", (player) => itemsMenu.show(player)
);

const goldenApple = new WikiEntry(
    "Golden Apple", "A rare and valuable food item.", "textures/ui/golden_apple.png", (player) => itemsMenu.show(player)
);

//MISC UI
const CATFISH_ITEM_UI = new WikiEntry({ translate: 'item.cc_aql:raw_catfish' }, { translate: 'cc_aql:guide.items.catfish', with: ['\n'] }, "textures/cc/aql/items/raw_catfish.png", (player) => itemsMenu.show(player));
const DIVING_SUIT_UI = new WikiEntry({ translate: 'item.cc_aql:diving_suit' }, { translate: 'cc_aql:guide.items.diving_suit', with: ['\n'] }, "textures/cc/aql/items/diving_helmet.png", (player) => itemsMenu.show(player));
const JELLYBALL_UI = new WikiEntry({ translate: 'item.cc_aql:jelly_ball' }, { translate: 'cc_aql:guide.items.jelly_ball', with: ['\n'] }, "textures/cc/aql/items/jelly_ball.png", (player) => itemsMenu.show(player));
const POLYMER_UI = new WikiEntry({ translate: 'item.cc_aql:organic_polymer' }, { translate: 'cc_aql:guide.items.organic_polymer', with: ['\n'] }, "textures/cc/aql/items/organic_polymer.png", (player) => itemsMenu.show(player));
const SCUBA_ARMOR_UI = new WikiEntry({ translate: 'item.cc_aql:scuba_armor' }, { translate: 'cc_aql:guide.items.scuba_armor', with: ['\n'] }, "textures/cc/aql/items/scuba_mask.png", (player) => itemsMenu.show(player));
const SHARK_TOOTH_UI = new WikiEntry({ translate: 'item.cc_aql:shark_tooth' }, { translate: 'cc_aql:guide.items.shark_tooth', with: ['\n'] }, "textures/cc/aql/items/shark_tooth.png", (player) => itemsMenu.show(player));
const SHARK_NECKLACE_UI = new WikiEntry({ translate: 'item.cc_aql:shark_tooth_necklace' }, { translate: 'cc_aql:guide.items.shark_necklace', with: ['\n'] }, "textures/cc/aql/items/shark_tooth_necklace.png", (player) => itemsMenu.show(player));
const SHARK_SWORD_UI = new WikiEntry({ translate: 'item.cc_aql:shark_tooth_sword' }, { translate: 'cc_aql:guide.items.shark_sword', with: ['\n'] }, "textures/cc/aql/items/shark_tooth_sword.png", (player) => itemsMenu.show(player));
const WORM_UI = new WikiEntry({ translate: 'item.cc_aql:worm' }, { translate: 'cc_aql:guide.items.worm', with: ['\n'] }, "textures/cc/aql/items/worm.png", (player) => itemsMenu.show(player));
//const WORM_BUCKET_UI = new WikiEntry({ translate: 'item.cc_aql:worm_bucket' }, { translate: 'cc_aql:guide.items.worm_bucket', with: ['\n'] }, "textures/cc/aql/items/worm_bucket.png", (player) => itemsMenu.show(player));
const NEON_DUST_UI = new WikiEntry({ translate: 'item.cc_aql:neon_dust' }, { translate: 'cc_aql:guide.items.neon_dust', with: ['\n'] }, "textures/cc/aql/items/neon_dust.png", (player) => itemsMenu.show(player));
const GUIDE_BOOK_UI = new WikiEntry({ translate: 'item.cc_aql:guide_book' }, { translate: 'cc_aql:guide.items.guide_book', with: ['\n'] }, "textures/cc/aql/items/guide_book.png", (player) => itemsMenu.show(player));

// ENTITY UI
const ANGLERFISH_UI = new WikiEntry({ translate: 'entity.cc_aql:anglerfish.name' }, { translate: 'cc_aql:guide.entity.anglerfish', with: ['\n'] }, "textures/cc/aql/ui/anglerfish_icon.png", (player) => entitiesMenu.show(player));
const CATFISH_UI = new WikiEntry({ translate: 'entity.cc_aql:catfish.name' }, { translate: 'cc_aql:guide.entity.catfish', with: ['\n'] }, "textures/cc/aql/ui/catfish_icon.png", (player) => entitiesMenu.show(player));
const EEL_UI = new WikiEntry({ translate: 'entity.cc_aql:eel.name' }, { translate: 'cc_aql:guide.entity.eel', with: ['\n'] }, "textures/cc/aql/ui/eel_icon.png", (player) => entitiesMenu.show(player));
const HAMMERHEAD_SHARK_UI = new WikiEntry({ translate: 'entity.cc_aql:hammerhead_shark.name' }, { translate: 'cc_aql:guide.entity.hammerhead_shark', with: ['\n'] }, "textures/cc/aql/ui/hammerhead_shark_icon.png", (player) => entitiesMenu.show(player));
const HUMPBACK_WHALE_UI = new WikiEntry({ translate: 'entity.cc_aql:humpback_whale.name' }, { translate: 'cc_aql:guide.entity.humpback_whale', with: ['\n'] }, "textures/cc/aql/ui/humpback_whale_icon.png", (player) => entitiesMenu.show(player));
const JELLYFISH_UI = new WikiEntry({ translate: 'entity.cc_aql:jellyfish.name' }, { translate: 'cc_aql:guide.entity.jellyfish', with: ['\n'] }, "textures/cc/aql/ui/jellyfish_icon.png", (player) => entitiesMenu.show(player));
const MANTARAY_UI = new WikiEntry({ translate: 'entity.cc_aql:mantaray.name' }, { translate: 'cc_aql:guide.entity.mantaray', with: ['\n'] }, "textures/cc/aql/ui/mantaray_icon.png", (player) => entitiesMenu.show(player));
const ORCA_UI = new WikiEntry({ translate: 'entity.cc_aql:orca.name' }, { translate: 'cc_aql:guide.entity.orca', with: ['\n'] }, "textures/cc/aql/ui/orca_icon.png", (player) => entitiesMenu.show(player));
const PELICAN_UI = new WikiEntry({ translate: 'entity.cc_aql:pelican.name' }, { translate: 'cc_aql:guide.entity.pelican', with: ['\n'] }, "textures/cc/aql/ui/pelican_icon.png", (player) => entitiesMenu.show(player));
const SEABUNNY_UI = new WikiEntry({ translate: 'entity.cc_aql:seabunny.name' }, { translate: 'cc_aql:guide.entity.seabunny', with: ['\n'] }, "textures/cc/aql/ui/seabunny_icon.png", (player) => entitiesMenu.show(player));
const SEAHORSE_UI = new WikiEntry({ translate: 'entity.cc_aql:seahorse.name' }, { translate: 'cc_aql:guide.entity.seahorse', with: ['\n'] }, "textures/cc/aql/ui/seahorse_icon.png", (player) => entitiesMenu.show(player));
const SWORDFISH_UI = new WikiEntry({ translate: 'entity.cc_aql:swordfish.name' }, { translate: 'cc_aql:guide.entity.swordfish', with: ['\n'] }, "textures/cc/aql/ui/swordfish_icon.png", (player) => entitiesMenu.show(player));
const WHITE_SHARK_UI = new WikiEntry({ translate: 'entity.cc_aql:white_shark.name' }, { translate: 'cc_aql:guide.entity.white_shark', with: ['\n'] }, "textures/cc/aql/ui/white_shark_icon.png", (player) => entitiesMenu.show(player));
const WORM_ENTITY_UI = new WikiEntry({ translate: 'entity.cc_aql:worm.name' }, { translate: 'cc_aql:guide.entity.worm', with: ['\n'] }, "textures/cc/aql/ui/worm_icon.png", (player) => entitiesMenu.show(player));

const BARRACUDA_UI = new WikiEntry({ translate: 'entity.cc_aql:barracuda.name' }, { translate: 'cc_aql:guide.entity.barracuda', with: ['\n'] }, "textures/cc/aql/ui/barracuda_icon.png", (player) => entitiesMenu.show(player));
const GLOWING_FISH_UI = new WikiEntry({ translate: 'entity.cc_aql:glowing_fish.name' }, { translate: 'cc_aql:guide.entity.glowing_fish', with: ['\n'] }, "textures/cc/aql/ui/glowing_fish_icon.png", (player) => entitiesMenu.show(player));
const LANTERN_FISH_UI = new WikiEntry({ translate: 'entity.cc_aql:lantern_fish.name' }, { translate: 'cc_aql:guide.entity.lantern_fish', with: ['\n'] }, "textures/cc/aql/ui/lantern_fish_icon.png", (player) => entitiesMenu.show(player));
const PIRANHA_UI = new WikiEntry({ translate: 'entity.cc_aql:piranha.name' }, { translate: 'cc_aql:guide.entity.piranha', with: ['\n'] }, "textures/cc/aql/ui/piranha_icon.png", (player) => entitiesMenu.show(player));
const SKULLFISH_UI = new WikiEntry({ translate: 'entity.cc_aql:skullfish.name' }, { translate: 'cc_aql:guide.entity.skullfish', with: ['\n'] }, "textures/cc/aql/ui/skullfish_icon.png", (player) => entitiesMenu.show(player));
const STINGRAY_UI = new WikiEntry({ translate: 'entity.cc_aql:stingray.name' }, { translate: 'cc_aql:guide.entity.stingray', with: ['\n'] }, "textures/cc/aql/ui/stingray_icon.png", (player) => entitiesMenu.show(player));

// MENUS UI
const entitiesMenu = new WikiMenu({
    title: "Entities",
    entries: [
        ANGLERFISH_UI, BARRACUDA_UI, CATFISH_UI, EEL_UI, GLOWING_FISH_UI, WHITE_SHARK_UI, HAMMERHEAD_SHARK_UI, HUMPBACK_WHALE_UI, JELLYFISH_UI, LANTERN_FISH_UI,
        MANTARAY_UI, ORCA_UI, PELICAN_UI, PIRANHA_UI, SEABUNNY_UI, SEAHORSE_UI, SKULLFISH_UI, STINGRAY_UI, SWORDFISH_UI, WORM_ENTITY_UI
    ],
    backFunction: (player) => showMainMenu(player)
}
);
const itemsMenu = new WikiMenu({
    title: "Items",
    entries: [
        CATFISH_ITEM_UI, DIVING_SUIT_UI, JELLYBALL_UI, NEON_DUST_UI, POLYMER_UI, SCUBA_ARMOR_UI, SHARK_TOOTH_UI,
        SHARK_NECKLACE_UI, SHARK_SWORD_UI, WORM_UI, GUIDE_BOOK_UI
    ],
    backFunction: (player) => showMainMenu(player)
});
const aboutMenu = new WikiMenu({
    title: "About",
    body: {translate: 'cc_aql:guide.about', with: ['\n']},
    entries: [],
    backFunction: (player) => showMainMenu(player)
});

function showMainMenu(player) {
    let form = new ActionFormData();
    form.title({ translate: 'cc_aql:guide.main.title' });
    form.body({ rawtext: [{ translate: 'cc_aql:guide.main', with: ['\n'] }] });

    form.button({ translate: 'cc_aql:guide.main.btn.items' });
    form.button({ translate: 'cc_aql:guide.main.btn.entities' });
    form.button({ translate: 'cc_aql:guide.main.btn.about' });

    form.show(player).then(response => {
        if (response.selection === null) return;

        if (response.selection === 0) {
            itemsMenu.show(player);
        } else if (response.selection === 1) {
            entitiesMenu.show(player);
        } else if (response.selection === 2) {
            aboutMenu.show(player);
        }
    });
}

mc.world.afterEvents.itemUse.subscribe((e) => {
    if (e.itemStack.typeId === GUIDE_BOOK_ITEM_ID) {
        showMainMenu(e.source);
    }
});

