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

export let defaultEXP = 10;
export const petsId = [
	'tp_pw:feral_lynx',
	'tp_pw:frost_fox',
	'tp_pw:flame_hawk',
	'tp_pw:music_golem',
	'tp_pw:nebula_dragon',
	'tp_pw:storm_griffin'
]
export const petList = [
	`§lFeral Lynx§r`,
	`§lFrost Fox§r`,
	`§lFlame Hawk§r`,
	`§lMusic Golem§r`,
	`§lNebula Dragon§r`,
	`§lStorm Griffin§r`,
	`PET`
]
let petID = null

{
const modeList = [
	`§l§2Neutral Mode§r`,
	`§l§dPassive Mode§r`,
	`§l§4Aggressive Mode§r`
]
function boostTime(value = undefined) {

    value ? world.setDynamicProperty("tp_pw:boost_time", value): null

    const tickBoost = system.runInterval(() => {

        // variable
        const time = world.getDynamicProperty("tp_pw:boost_time")
        if (time === 0) {

            system.clearRun(tickBoost)
            world.sendMessage({ translate: "settings.tp_pw.boost.end" })
            return


        } else if (time === 180) {

            world.sendMessage({ translate: "settings.tp_pw.boost.2" })


        } else if (time === 60) {

            world.sendMessage({ translate: "settings.tp_pw.boost.4" })


        } else if (time === 30) {

            world.sendMessage({ translate: "settings.tp_pw.boost.5" })


        } else if (time === 10) {

            world.sendMessage({ translate: "settings.tp_pw.boost.6" })


        } else if (time === 5) {

            world.sendMessage({ translate: "settings.tp_pw.boost.7" })


        } else if (time === 4) {

            world.sendMessage({ translate: "settings.tp_pw.boost.8" })


        } else if (time === 3) {

            world.sendMessage({ translate: "settings.tp_pw.boost.9" })


        } else if (time === 2) {

            world.sendMessage({ translate: "settings.tp_pw.boost.10" })


        } else if (time === 1) {

            world.sendMessage({ translate: "settings.tp_pw.boost.11" })


        }
        world.setDynamicProperty("tp_pw:boost_time", time - 1)
    }, 1*20)
}
//New HUD
function mainMenu(player) {

    player.playSound("item.book.page_turn", { pitch: 1.0, volume: 1.0 })
    instanceMenu(

        player,
        { translate: "settings.tp_pw.main.title"},
        { translate: "settings.tp_pw.main.body"},
        [
			{
                text: { translate: "settings.tp_pw.wp_lvl_hud.button" },
                image: "textures/tp/pw/settings/weapons_settings",
                command: () => {
                    player.playSound("item.book.page_turn", { pitch: 1.0, volume: 1.0 })
                    wpLevelHUD(player)
                }
            },
			{
                text: { translate: "settings.tp_pw.pet_lvl_hud.button" },
                image: "textures/tp/pw/settings/pets_settings",
                command: () => {
                    player.playSound("item.book.page_turn", { pitch: 1.0, volume: 1.0 })
                    newPetLevelHUD(player)
                }
            },
            {
                text: { translate: "settings.tp_pw.petData.button" },
                image: "textures/tp/pw/settings/pet_data_settings",
                command: () => {
                    player.playSound("item.book.page_turn", { pitch: 1.0, volume: 1.0 })
                    petDataMenu(player)
                }
            },
            {
                text: { translate: "settings.tp_pw.sounds.button" },
                image: "textures/tp/pw/settings/music_settings",
                command: () => {
                    player.playSound("item.book.page_turn", { pitch: 1.0, volume: 1.0 })
                    soundsMenu(player)
                }
            },
            {
                text: { translate: "settings.tp_pw.difficulty.button" },
                image: "textures/tp/pw/settings/difficulty_settings",
                command: () => {
                    player.playSound("item.book.page_turn", { pitch: 1.0, volume: 1.0 })
                    difficultyMenu(player)
                }
            },
            {
                text: { translate: "settings.tp_pw.leveling.button" },
                image: "textures/tp/pw/settings/leveling_system_settings",
                command: () => {
                    player.playSound("item.book.page_turn", { pitch: 1.0, volume: 1.0 })
                    levelingMenu(player)
                }
            },
            {
                text: { translate: "settings.tp_pw.cinematic.button" },
                image: "textures/tp/pw/settings/cinematic_effects_settings",
                command: () => {
                    player.playSound("item.book.page_turn", { pitch: 1.0, volume: 1.0 })
                    cameraMenu(player)
                }
            },
            {
                text: { translate: "settings.tp_pw.pvp.button" },
                image: "textures/tp/pw/settings/pvp_settings",
                command: () => {
                    player.playSound("item.book.page_turn", { pitch: 1.0, volume: 1.0 })
                    pvpMenu(player)
                }
            }
        ]
    )
}
function soundsMenu(player) {
    world.getDynamicProperty("tp_pw:sound") === undefined ? world.setDynamicProperty("tp_pw:sound", true): null
    world.getDynamicProperty("tp_pw:sound") === false
    ? instanceMenu(
        player,
        { translate: "settings.tp_pw.sound.title"},
        { translate: "settings.tp_pw.sound_off.body", with: ["\n"] },
        [
            {
                text: { translate: "settings.tp_pw.sound.on.button" },
                image: "textures/tp/pw/settings/music_settings",
                command: () => {
                    world.setDynamicProperty("tp_pw:sound", true)
                    world.sendMessage({ translate: "settings.tp_pw.effect_sound.toggle_on" })
                    player.playSound("note.hat", { pitch: 1.0, volume: 1.0 })
                    soundsMenu(player)
                }
            },
            {
                text: { translate: "settings.tp_pw.back.button" },
                image: "textures/tp/pw/settings/back",
                command: () => { mainMenu(player) }
            }
        ]
    )
    : instanceMenu(
        player,
        { translate: "settings.tp_pw.sound.on.button"},
        { translate: "settings.tp_pw.sound_on.body", with: ["\n"] },
        [
            {
                text: { translate: "settings.tp_pw.sound.off.button" },
                image: "textures/tp/pw/settings/music_settings",
                command: () => {
                    world.setDynamicProperty("tp_pw:sound", false)
                    player.playSound("note.hat", { pitch: 1.0, volume: 1.0 })
                    world.sendMessage({ translate: "settings.tp_pw.effect_sound.toggle_off" })
                    soundsMenu(player)
                }
            },
            {
                text: { translate: "settings.tp_pw.back.button" },
                image: "textures/tp/pw/settings/back",
                command: () => { mainMenu(player) }
            }
        ]
    )
}
function pvpMenu(player) {
    world.getDynamicProperty("tp_pw:pvp") === undefined ? world.setDynamicProperty("tp_pw:pvp", false): null
    world.getDynamicProperty("tp_pw:pvp") === false
    ? instanceMenu(
        player,
        { translate: "settings.tp_pw.pvp.title"},
        { translate: "settings.tp_pw.pvp_off.body", with: ["\n"] },
        [
            {
                text: { translate: "settings.tp_pw.pvp.on.button" },
                image: "textures/tp/pw/settings/pvp_settings",
                command: () => {
                    world.setDynamicProperty("tp_pw:pvp", true)
                    world.sendMessage({ translate: "settings.tp_pw.effect_pvp.toggle_on" })
                    player.playSound("note.hat", { pitch: 1.0, volume: 1.0 })
                    pvpMenu(player)
                }
            },
            {
                text: { translate: "settings.tp_pw.back.button" },
                image: "textures/tp/pw/settings/back",
                command: () => { mainMenu(player) }
            }
        ]
    )
    : instanceMenu(
        player,
        { translate: "settings.tp_pw.pvp.on.button"},
        { translate: "settings.tp_pw.pvp_on.body", with: ["\n"] },
        [
            {
                text: { translate: "settings.tp_pw.pvp.off.button" },
                image: "textures/tp/pw/settings/pvp_settings",
                command: () => {
                    world.setDynamicProperty("tp_pw:pvp", false)
                    player.playSound("note.hat", { pitch: 1.0, volume: 1.0 })
                    world.sendMessage({ translate: "settings.tp_pw.effect_pvp.toggle_off" })
                    pvpMenu(player)
                }
            },
            {
                text: { translate: "settings.tp_pw.back.button" },
                image: "textures/tp/pw/settings/back",
                command: () => { mainMenu(player) }
            }
        ]
    )
}
function levelingMenu(player) {

    world.getDynamicProperty("tp_pw:boost_time") === undefined ? world.setDynamicProperty("tp_pw:boost_time", 0): null

    world.getDynamicProperty("tp_pw:boost_time") === 0
    ? instanceMenu(  // not active boost

        player,
        { translate: "settings.tp_pw.leveling.title" },
        { translate: "settings.tp_pw.leveling_off.body" },
        [
            {
                text: { translate: "settings.tp_pw.boost.button" },
                image: "textures/tp/pw/settings/boost_settings",
                command: () => {

                    player.playSound("note.snare", { pitch: 1.0, volume: 1.0 })
                    // boost system
                    instanceMenu(

                        player,
                        { translate: "settings.tp_pw.leveling.title" },
                        { translate: "settings.tp_pw.leveling_boost.body" },
                        [
                            {
                                text: { translate: "settings.tp_pw.boost_activate.button" },
                                image: "textures/tp/pw/settings/boost_settings",
                                command: () => {

                                    const itemQuery = getItemOnInventory(player, "minecraft:diamond")
                                    if (itemQuery?.amount >= 1) {

                                        player.playSound("note.pling", { pitch: 1.0, volume: 1.0 })
                                        player.runCommand("clear @s diamond 0 1")
                                        boostTime(300)
                                        world.sendMessage({ translate: "settings.tp_pw.boost.activate", with: [player.nameTag] })
                                        instanceMenu(

                                            player,
                                            { translate: "settings.tp_pw.leveling.title" },
                                            { translate: "settings.tp_pw.leveling_boost_activate.body" },
                                            [
                                                {
                                                    text: { translate: "settings.tp_pw.back.button" },
                                                    image: "textures/tp/pw/settings/back",
                                                    command: () => {
                                                        
                                                        levelingMenu(player)
                                                        player.playSound("item.book.page_turn", { pitch: 1.0, volume: 1.0 })
                                                    
                                                    
                                                    }
                                                    
                                                }
                                            ]
                                    
                                    
                                        )

                                    } else {

                                        instanceMenu(

                                            player,
                                            { translate: "settings.tp_pw.leveling.title" },
                                            { translate: "settings.tp_pw.leveling_boost_fail.body" },
                                            [
                                                {
                                                    text: { translate: "settings.tp_pw.back.button" },
                                                    image: "textures/tp/pw/settings/back",
                                                    command: () => { levelingMenu(player); player.playSound("item.book.page_turn", { pitch: 1.0, volume: 1.0 }) }
                                                    
                                                }
                                            ]
                                    
                                    
                                        )


                                    }
                
                
                                }
                                
                            },
                            {
                                text: { translate: "settings.tp_pw.back.button" },
                                image: "textures/tp/pw/settings/back",
                                command: () => { levelingMenu(player); player.playSound("item.book.page_turn", { pitch: 1.0, volume: 1.0 }) }
                                
                            }
                        ]
                
                
                    )


                }
                
            },
            {
                text: { translate: "settings.tp_pw.reset.button" },
                image: "textures/tp/pw/settings/reset_settings",
                command: () => {
                
                    player.playSound("note.snare", { pitch: 1.0, volume: 1.0 })
                    instanceMenu(

                        player,
                        { translate: "settings.tp_pw.leveling.title" },
                        { translate: "settings.tp_pw.leveling_reset.body" },
                        [
                            {
                                text: { translate: "settings.tp_pw.reset.button" },
                                image: "textures/tp/pw/settings/reset_settings",
                                command: () => {

                                    player.playSound("note.snare", { pitch: 1.0, volume: 1.0 })
                                    instanceMenu(

                                        player,
                                        { translate: "settings.tp_pw.leveling.title" },
                                        { translate: "settings.tp_pw.leveling_reset_confirm.body" },
                                        [
                                            {
                                                text: { translate: "settings.tp_pw.reset_confirm.button" },
                                                image: "textures/tp/pw/settings/reset_settings",
                                                command: () => {

                                                    
                                                    const itemQuery = getItemOnInventory(player, "minecraft:diamond")
                                                    if (itemQuery?.amount >= 1) {
                                                        
                                                        player.runCommandAsync("clear @s diamond 0 1");
                                                        world.getAllPlayers().forEach(player => {
                                                            resetLevel()
                                                          })
                                                          player.playSound("note.pling", { pitch: 1.0, volume: 1.0 })
                                                          world.sendMessage({ translate: "settings.tp_pw.stats.reset" })
                                                          instanceMenu(

                                                            player,
                                                            { translate: "settings.tp_pw.leveling.title" },
                                                            { translate: "settings.tp_pw.leveling_reset_complete.body" },
                                                            [
                                                                {
                                                                    text: { translate: "settings.tp_pw.back.button" },
                                                                    image: "textures/tp/pw/settings/back",
                                                                    command: () => { levelingMenu(player); player.playSound("item.book.page_turn", { pitch: 1.0, volume: 1.0 }) }

                                                                }
                                                            ]
                                                        
                                                        
                                                        )


                                                    } else {
                
                                                        instanceMenu(
                
                                                            player,
                                                            { translate: "settings.tp_pw.leveling.title" },
                                                            { translate: "settings.tp_pw.leveling_boost_fail.body" },
                                                            [
                                                                {
                                                                    text: { translate: "settings.tp_pw.back.button" },
                                                                    image: "textures/tp/pw/settings/back",
                                                                    command: () => { levelingMenu(player); player.playSound("item.book.page_turn", { pitch: 1.0, volume: 1.0 }) }
                                                                    
                                                                }
                                                            ]
                                                    
                                                    
                                                        )
                
                
                                                    }


                                                }
                                                
                                            },
                                            {
                                                text: { translate: "settings.tp_pw.back.button" },
                                                image: "textures/tp/pw/settings/back",
                                                command: () => { levelingMenu(player); player.playSound("item.book.page_turn", { pitch: 1.0, volume: 1.0 }) }
                                                
                                            }
                                        ]
                                
                                
                                    )

                                    
                                }
                                
                            },
                            {
                                text: { translate: "settings.tp_pw.back.button" },
                                image: "textures/tp/pw/settings/back",
                                command: () => { levelingMenu(player); player.playSound("item.book.page_turn", { pitch: 1.0, volume: 1.0 }) }
                                
                            }
                        ]
                
                
                    )


                }
                
            },
            {
                text: { translate: "settings.tp_pw.back.button" },
                image: "textures/tp/pw/settings/back",
                command: () => { mainMenu(player) }
                
            },
        ]


    )
    : instanceMenu(  // actived boost

        player,
        { translate: "settings.tp_pw.leveling.title" },
        { translate: "settings.tp_pw.leveling_on.body" },
        [
            {
                text: { translate: "settings.tp_pw.reset.button" },
                image: "textures/tp/pw/settings/reset_settings",
                command: () => {
                
                    player.playSound("note.snare", { pitch: 1.0, volume: 1.0 })
                    instanceMenu(

                        player,
                        { translate: "settings.tp_pw.leveling.title" },
                        { translate: "settings.tp_pw.leveling_reset.body" },
                        [
                            {
                                text: { translate: "settings.tp_pw.reset.button" },
                                image: "textures/tp/pw/settings/reset_settings",
                                command: () => {

                                    player.playSound("note.snare", { pitch: 1.0, volume: 1.0 })
                                    instanceMenu(

                                        player,
                                        { translate: "settings.tp_pw.leveling.title" },
                                        { translate: "settings.tp_pw.leveling_reset_confirm.body" },
                                        [
                                            {
                                                text: { translate: "settings.tp_pw.reset_confirm.button" },
                                                image: "textures/tp/pw/settings/reset_settings",
                                                command: () => {

                                                    
                                                    const itemQuery = getItemOnInventory(player, "minecraft:diamond")
                                                    if (itemQuery?.amount >= 1) {
                                                        
                                                        player.runCommandAsync("clear @s diamond 0 1");
                                                        world.getAllPlayers().forEach(player => {
                                                            resetLevel()
                                                          })
                                                          player.playSound("note.pling", { pitch: 1.0, volume: 1.0 })
                                                          world.sendMessage({ translate: "settings.tp_pw.stats.reset" })
                                                          instanceMenu(

                                                            player,
                                                            { translate: "settings.tp_pw.leveling.title" },
                                                            { translate: "settings.tp_pw.leveling_reset_complete.body" },
                                                            [
                                                                {
                                                                    text: { translate: "settings.tp_pw.back.button" },
                                                                    image: "textures/tp/pw/settings/back",
                                                                    command: () => { levelingMenu(player); player.playSound("item.book.page_turn", { pitch: 1.0, volume: 1.0 }) }

                                                                }
                                                            ]
                                                        
                                                        
                                                        )


                                                    } else {
                
                                                        instanceMenu(
                
                                                            player,
                                                            { translate: "settings.tp_pw.leveling.title" },
                                                            { translate: "settings.tp_pw.leveling_boost_fail.body" },
                                                            [
                                                                {
                                                                    text: { translate: "settings.tp_pw.back.button" },
                                                                    image: "textures/tp/pw/settings/back",
                                                                    command: () => { levelingMenu(player); player.playSound("item.book.page_turn", { pitch: 1.0, volume: 1.0 }) }
                                                                    
                                                                }
                                                            ]
                                                    
                                                    
                                                        )
                
                
                                                    }


                                                }
                                                
                                            },
                                            {
                                                text: { translate: "settings.tp_pw.back.button" },
                                                image: "textures/tp/pw/settings/back",
                                                command: () => { levelingMenu(player); player.playSound("item.book.page_turn", { pitch: 1.0, volume: 1.0 }) }
                                                
                                            }
                                        ]
                                
                                
                                    )

                                    
                                }
                                
                            },
                            {
                                text: { translate: "settings.tp_pw.back.button" },
                                image: "textures/tp/pw/settings/back",
                                command: () => { levelingMenu(player); player.playSound("item.book.page_turn", { pitch: 1.0, volume: 1.0 }) }
                                
                            }
                        ]
                
                
                    )


                }
                
            },
            {
                text: { translate: "settings.tp_pw.back.button" },
                image: "textures/tp/pw/settings/back",
                command: () => { mainMenu(player) }
                
            },
        ]


    )


}
function cameraMenu(player) {

    // defines default
    world.getDynamicProperty("tp_pw:camera") === undefined ? world.setDynamicProperty("tp_pw:camera", true): null

    // togle
    world.getDynamicProperty("tp_pw:camera") === false
    ? instanceMenu(

        player,
        { translate: "settings.tp_pw.camera.title"},
        { translate: "settings.tp_pw.camera_off.body", with: ["\n"] },
        [
            {
                text: { translate: "settings.tp_pw.camera.on.button" },
                image: "textures/tp/pw/settings/switch_off_settings",
                command: () => {

                    world.setDynamicProperty("tp_pw:camera", true)
                    player.playSound("note.hat", { pitch: 1.0, volume: 1.0 })
                    world.sendMessage({ translate: "settings.tp_pw.cinematic_effect.toggle_on" })
                    cameraMenu(player)


                }
                
            },
            {
                text: { translate: "settings.tp_pw.back.button" },
                image: "textures/tp/pw/settings/back",
                command: () => { mainMenu(player) }
                
            }
        ]


    )
    : instanceMenu(

        player,
        { translate: "settings.tp_pw.camera.title"},
        { translate: "settings.tp_pw.camera_on.body", with: ["\n"] },
        [
            {
                text: { translate: "settings.tp_pw.camera.off.button" },
                image: "textures/tp/pw/settings/switch_on_settings",
                command: () => {

                    world.setDynamicProperty("tp_pw:camera", false)
                    player.playSound("note.hat", { pitch: 1.0, volume: 1.0 })
                    world.sendMessage({ translate: "settings.tp_pw.cinematic_effect.toggle_off" })
                    cameraMenu(player)


                }
                
            },
            {
                text: { translate: "settings.tp_pw.back.button" },
                image: "textures/tp/pw/settings/back",
                command: () => { mainMenu(player) }
                
            }
        ]


    )


}
function difficultyMenu(player) {

    instanceMenu(

        player,
        { translate: "settings.tp_pw.difficulty.title" },
        { translate: "settings.tp_pw.difficulty.body" },
        [
            {
                text: { translate: "settings.tp_pw.diff_e.button" },
                image: "textures/tp/pw/settings/difficulty_easy_settings",
                command: () => {

                    player.runCommand("difficulty e")
                    player.playSound("note.hat", { pitch: 1.0, volume: 1.0 })
                    world.sendMessage({ translate: "settings.tp_pw.difficulty.change.easy" })
                    world.setDynamicProperty('tp_pw:difficulty',0)
                    difficultyMenu(player)


                }
                
            },
            {
                text: { translate: "settings.tp_pw.diff_n.button" },
                image: "textures/tp/pw/settings/difficulty_normal_settings",
                command: () => {

                    player.runCommand("difficulty n")
                    player.playSound("note.hat", { pitch: 1.0, volume: 1.0 })
                    world.sendMessage({ translate: "settings.tp_pw.difficulty.change.normal" })
                    world.setDynamicProperty('tp_pw:difficulty',1)
                    difficultyMenu(player)


                }
                
            },
            {
                text: { translate: "settings.tp_pw.diff_h.button" },
                image: "textures/tp/pw/settings/difficulty_hard_settings",
                command: () => {

                    player.runCommand("difficulty h")
                    player.playSound("note.hat", { pitch: 1.0, volume: 1.0 })
                    world.sendMessage({ translate: "settings.tp_pw.difficulty.change.hard" })
                    world.setDynamicProperty('tp_pw:difficulty',2)
                    difficultyMenu(player)

                }
                
            },
            {
                text: { translate: "settings.tp_pw.back.button" },
                image: "textures/tp/pw/settings/back",
                command: () => { mainMenu(player) }
                
            }
        ]


    )
}
function petDataMenu(player) {
    player.getDynamicProperty("tp_pw:petData") === undefined ? player.setDynamicProperty("tp_pw:petData", true): null
    player.getDynamicProperty("tp_pw:petData") === false
    ? instanceMenu(
        player,
        { translate: "settings.tp_pw.petData.title"},
        { translate: "settings.tp_pw.petData_off.body", with: ["\n"] },
        [
            {
                text: { translate: "settings.tp_pw.petData.on.button" },
                image: "textures/tp/pw/settings/pet_data_settings",
                command: () => {
                    player.setDynamicProperty("tp_pw:petData", true)
                    player.sendMessage({ translate: "settings.tp_pw.pet_data.toggle_on" })
                    player.playSound("note.hat", { pitch: 1.0, volume: 1.0 })
                    petDataMenu(player)
                }
            },
            {
                text: { translate: "settings.tp_pw.back.button" },
                image: "textures/tp/pw/settings/back",
                command: () => { mainMenu(player) }
            }
        ]
    )
    : instanceMenu(
        player,
        { translate: "settings.tp_pw.petData.on.button"},
        { translate: "settings.tp_pw.petData_on.body", with: ["\n"] },
        [
            {
                text: { translate: "settings.tp_pw.petData.off.button" },
                image: "textures/tp/pw/settings/pet_data_settings",
                command: () => {
                    player.setDynamicProperty("tp_pw:petData", false)
                    player.playSound("note.hat", { pitch: 1.0, volume: 1.0 })
                    player.sendMessage({ translate: "settings.tp_pw.pet_data.toggle_off" })
                    petDataMenu(player)
                }
            },
            {
                text: { translate: "settings.tp_pw.back.button" },
                image: "textures/tp/pw/settings/back",
                command: () => { mainMenu(player) }
            }
        ]
    )
}
//Old HUD
function mainHUD(player) {
	const form = new ActionFormData()
		.title('§l§2PET WEAPONS')
		.body(`
§l§e[§bPet Weapons §2Main Menu§e]§r`)
		.button('§l§1Level Stats')
		.button('§l§1Settings')
		.button('§l§4Close')
	form.show(player).then((response = ActionFormResponse) => {
		if (response.selection === 0) {
			levelHUD(player)
		}
		if (response.selection === 1) {
			settingsHUD(player)
		}
	})
}
function levelHUD(player) {
	const form = new ActionFormData()
		.title('§l§2PET WEAPONS')
		.body(`
§l§e[§bSelect Level Stats§e]§r`)
		.button('§l§5Weapons §9Level Stats')
		.button('§l§5Pets §9Level Stats')
		.button('§l§4Close')
	form.show(player).then((response = ActionFormResponse) => {
		if (response.selection === 0) {
			wpLevelHUD(player)
		}
		if (response.selection === 1) {
			petLevelHUD(player)
		}
	})
}
function wpLevelHUD(player) {
    let SBbotwEXP = world.scoreboard.getObjective(`tp_pw:blade_of_the_wild_EXP`);
    let SBbotwLVL = world.scoreboard.getObjective(`tp_pw:blade_of_the_wild_LVL`);
    let SBcgEXP = world.scoreboard.getObjective(`tp_pw:celestial_gauntlets_EXP`);
    let SBcgLVL = world.scoreboard.getObjective(`tp_pw:celestial_gauntlets_LVL`);
    let SBebEXP = world.scoreboard.getObjective(`tp_pw:ember_bow_EXP`);
    let SBebLVL = world.scoreboard.getObjective(`tp_pw:ember_bow_LVL`);
    let SBgsEXP = world.scoreboard.getObjective(`tp_pw:glacier_staff_EXP`);
    let SBgsLVL = world.scoreboard.getObjective(`tp_pw:glacier_staff_LVL`);
    let SBmfEXP = world.scoreboard.getObjective(`tp_pw:mystic_flute_EXP`);
    let SBmfLVL = world.scoreboard.getObjective(`tp_pw:mystic_flute_LVL`);
    let SBtmEXP = world.scoreboard.getObjective(`tp_pw:thunder_mace_EXP`);
    let SBtmLVL = world.scoreboard.getObjective(`tp_pw:thunder_mace_LVL`);
    const lvl = [
        world.scoreboard.getObjective(`tp_pw:blade_of_the_wild_LVL`),
        world.scoreboard.getObjective(`tp_pw:celestial_gauntlets_LVL`),
        world.scoreboard.getObjective(`tp_pw:ember_bow_LVL`),
        world.scoreboard.getObjective(`tp_pw:glacier_staff_LVL`),
        world.scoreboard.getObjective(`tp_pw:mystic_flute_LVL`),
        world.scoreboard.getObjective(`tp_pw:thunder_mace_LVL`),
    ]
    const ult = [
        world.scoreboard.getObjective(`tp_pw:blade_of_the_wild_ULT`),
        world.scoreboard.getObjective(`tp_pw:celestial_gauntlets_ULT`),
        world.scoreboard.getObjective(`tp_pw:ember_bow_ULT`),
        world.scoreboard.getObjective(`tp_pw:glacier_staff_ULT`),
        world.scoreboard.getObjective(`tp_pw:mystic_flute_ULT`),
        world.scoreboard.getObjective(`tp_pw:thunder_mace_ULT`),
    ]
	const form = new ActionFormData()
		.title('Weapons Level Stats')
		.body(`
§lWeapon Levels Info§r \n
§l§a[§e-§a]§r§9 §dBlade of The Wild§r
        §6EXP: §e${SBbotwEXP.getScore(player)}§r/§e${(defaultEXP * (SBbotwLVL.getScore(player)))*0.8}
        §6LVL: §e${SBbotwLVL.getScore(player)}\n`+(lvl[0].getScore(player) >= 5 && ult[0].getScore(player) < 10 ? `        §6Ultimate: §6${'/'.repeat(ult[0].getScore(player))}§j${'/'.repeat(10 - ult[0].getScore(player))}\n` : lvl[0].getScore(player) >= 5 && ult[0].getScore(player) >= 10 ? `        §6Ultimate: §e//////////\n`: ``) +
    `§l§a[§e-§a]§r§9 §dCelestial Gauntlets§r
        §6EXP: §e${SBcgEXP.getScore(player)}§r/§e${(defaultEXP * (SBcgLVL.getScore(player)))*0.8}
        §6LVL: §e${SBcgLVL.getScore(player)}\n`+(lvl[1].getScore(player) >= 5 && ult[1].getScore(player) < 10 ? `        §6Ultimate: §6${'/'.repeat(ult[1].getScore(player))}§j${'/'.repeat(10 - ult[1].getScore(player))}\n` : lvl[1].getScore(player) >= 5 && ult[1].getScore(player) >= 10 ? `        §6Ultimate: §e//////////\n`: ``) +
    `§l§a[§e-§a]§r§9 §dEmber Bow§r
        §6EXP: §e${SBebEXP.getScore(player)}§r/§e${(defaultEXP * (SBebLVL.getScore(player)))*0.8}
        §6LVL: §e${SBebLVL.getScore(player)}\n`+(lvl[2].getScore(player) >= 5 && ult[2].getScore(player) < 10 ? `        §6Ultimate: §6${'/'.repeat(ult[2].getScore(player))}§j${'/'.repeat(10 - ult[2].getScore(player))}\n` : lvl[2].getScore(player) >= 5 && ult[2].getScore(player) >= 10 ? `        §6Ultimate: §e//////////\n`: ``) +
    `§l§a[§e-§a]§r§9 §dGlacier Staff§r
        §6EXP: §e${SBgsEXP.getScore(player)}§r/§e${(defaultEXP * (SBgsLVL.getScore(player)))*0.8}
        §6LVL: §e${SBgsLVL.getScore(player)}\n`+(lvl[3].getScore(player) >= 5 && ult[3].getScore(player) < 10 ? `        §6Ultimate: §6${'/'.repeat(ult[3].getScore(player))}§j${'/'.repeat(10 - ult[3].getScore(player))}\n` : lvl[3].getScore(player) >= 5 && ult[3].getScore(player) >= 10 ? `        §6Ultimate: §e//////////\n`: ``) +
    `§l§a[§e-§a]§r§9 §dMystic Flute§r
        §6EXP: §e${SBmfEXP.getScore(player)}§r/§e${(defaultEXP * (SBmfLVL.getScore(player)))*0.8}
        §6LVL: §e${SBmfLVL.getScore(player)}\n`+(lvl[4].getScore(player) >= 5 && ult[4].getScore(player) < 10 ? `        §6Ultimate: §6${'/'.repeat(ult[4].getScore(player))}§j${'/'.repeat(10 - ult[4].getScore(player))}\n` : lvl[4].getScore(player) >= 5 && ult[4].getScore(player) >= 10 ? `        §6Ultimate: §e//////////\n`: ``) +
    `§l§a[§e-§a]§r§9 §dThunder Mace§r
        §6EXP: §e${SBtmEXP.getScore(player)}§r/§e${(defaultEXP * (SBtmLVL.getScore(player)))*0.8}
        §6LVL: §e${SBtmLVL.getScore(player)}\n`+(lvl[5].getScore(player) >= 5 && ult[5].getScore(player) < 10 ? `        §6Ultimate: §6${'/'.repeat(ult[5].getScore(player))}§j${'/'.repeat(10 - ult[5].getScore(player))}\n` : lvl[5].getScore(player) >= 5 && ult[5].getScore(player) >= 10 ? `        §6Ultimate: §e//////////\n`: ``) +
    ``)
		.button({ translate: "settings.tp_pw.back.button" }, "textures/tp/pw/settings/back")
	form.show(player).then((response = ActionFormResponse) => {
		if (response.selection === 0) {
			mainMenu(player)
		}
	})
}
function petLevelHUD(player) {
    let entityList = [];
    let entityDataList = [];
    player.dimension.getEntities({tags: [`tp_pw:${player.id}`]}).forEach(pet => {
		let chosenPet = null
		switch (pet.typeId) {
			case `tp_pw:feral_lynx`:
				chosenPet = 0
				break;
			case `tp_pw:frost_fox`:
				chosenPet = 1
				break;
			case `tp_pw:flame_hawk`:
				chosenPet = 2
				break;
			case `tp_pw:music_golem`:
				chosenPet = 3
				break;
			case `tp_pw:nebula_dragon`:
				chosenPet = 4
				break;
			case `tp_pw:storm_griffin`:
				chosenPet = 5
				break;
		
			default:
				chosenPet = 6
				break;
		}
		entityList.push(pet.nameTag? `${petList[chosenPet]} - ${pet.nameTag}`: `${petList[chosenPet]}`);
        entityDataList.push(pet);
    });
	if(entityList.length>0){
		new ModalFormData()
			.title({translate:'settings.tp_pw.pet_stats.title'})
			.dropdown(
				{translate:'settings.tp_pw.pet_stats.body'},
				entityList
			)
			.show(player)
			.then((r) => {
				const selectedPet = entityDataList[r.formValues[0]];
				if (selectedPet) {
					showPetInfoHUD(player, selectedPet);
				}
			});
	} else if (entityList.length===0){
		player.playSound("item.book.page_turn", { pitch: 1.0, volume: 1.0 })
		instanceMenu(
	
			player,
			{ translate: "settings.tp_pw.no_pet_found.title"},
			{ translate: "settings.tp_pw.no_pet_found.body"},
			[
				{
					text: { translate: "settings.tp_pw.back.button" },
					image: "textures/tp/pw/settings/back",
					command: () => { mainMenu(player) }
				}
			]
		)
	}
}
function newPetLevelHUD(player) {
    let entityList = [];
    let entityDataList = [];
    let buttonList = []
    player.dimension.getEntities({tags: [`tp_pw:${player.id}`]}).forEach(pet => {
		let chosenPet = null
		switch (pet.typeId) {
			case `tp_pw:feral_lynx`:
				chosenPet = 0
				break;
			case `tp_pw:frost_fox`:
				chosenPet = 1
				break;
			case `tp_pw:flame_hawk`:
				chosenPet = 2
				break;
			case `tp_pw:music_golem`:
				chosenPet = 3
				break;
			case `tp_pw:nebula_dragon`:
				chosenPet = 4
				break;
			case `tp_pw:storm_griffin`:
				chosenPet = 5
				break;
		
			default:
				chosenPet = 0
				break;
		}
		entityList.push(pet.nameTag? `${petList[chosenPet]} - ${pet.nameTag}`: `${petList[chosenPet]}`);
        entityDataList.push(pet);


        const button = {
            text: pet.nameTag? `${petList[chosenPet]} - ${pet.nameTag}`: `${petList[chosenPet]}`,
            image: `textures/tp/pw/settings/pets/${chosenPet}`,
            command: () =>{
                showPetInfoHUD(player, pet)
            }
        }
        buttonList.push(button)
    });
    const backButton = {
        text: { translate: "settings.tp_pw.back.button" },
        image: "textures/tp/pw/settings/back",
        command: () =>{
            mainMenu(player)
        }
    }
    buttonList.push(backButton)
	if(buttonList.length>1){
        instanceMenu(
            player,
            {translate: 'settings.tp_pw.newPetLevelHud.title'},
            {translate: 'settings.tp_pw.newPetLevelHud.body'},
            buttonList
        )
	} else if (entityList.length===0){
		player.playSound("item.book.page_turn", { pitch: 1.0, volume: 1.0 })
		instanceMenu(
	
			player,
			{ translate: "settings.tp_pw.no_pet_found.title"},
			{ translate: "settings.tp_pw.no_pet_found.body"},
			[
				{
					text: { translate: "settings.tp_pw.back.button" },
					image: "textures/tp/pw/settings/back",
					command: () => { mainMenu(player) }
				}
			]
		)
	}
}
function healthDisplayer(entity) {
    const health = entity.getComponent("minecraft:health")
    const totalBars = 10;
    const healthPercent = health.currentValue / health.defaultValue;
    const healthBars = Math.round(healthPercent * totalBars);
    
    const greenBar = '+'.repeat(healthBars);
    const redBar = '+'.repeat(totalBars - healthBars);
    return `§c§l${greenBar}§j${redBar}`;
}
function hungerDisplayer(entity) {
    const hgr = world.scoreboard.getObjective('tp_pw:pet_HGR')
    const totalBars = 10;
    const healthPercent = hgr.getScore(entity) / 600;
    const healthBars = Math.round(healthPercent * totalBars);
    
    const greenBar = '#'.repeat(healthBars);
    const redBar = '#'.repeat(totalBars - healthBars);
    return `§r§g${greenBar}§j${redBar}`;
}
function modeDisplayer(mode) {
    switch (mode) {
        case 'passive': 
            return `§l§dPassive`;
        case 'neutral':
            return `§l§2Neutral`;
        case 'aggressive':
            return `§l§4Aggressive`;
        default:
            return 'Unknown mode';  // Menambahkan nilai default jika mode tidak cocok
    }
}
function showPetInfoHUD(player, selectedPet, quickOption = false) {
    let petEXP = world.scoreboard.getObjective(`tp_pw:pet_EXP`);
    let petLVL = world.scoreboard.getObjective(`tp_pw:pet_LVL`);
    let pet_HGR = world.scoreboard.getObjective(`tp_pw:pet_HGR`);
	const pet = selectedPet
	let warn = ``
	let chosenPet = null
	switch (selectedPet.typeId) {
		case `tp_pw:feral_lynx`:
			chosenPet = 0
			break;
		case `tp_pw:frost_fox`:
			chosenPet = 1
			break;
		case `tp_pw:flame_hawk`:
			chosenPet = 2
			break;
		case `tp_pw:music_golem`:
			chosenPet = 3
			break;
		case `tp_pw:nebula_dragon`:
			chosenPet = 4
			break;
		case `tp_pw:storm_griffin`:
			chosenPet = 5
			break;
	
		default:
			chosenPet = 6
			break;
	}
	if (pet_HGR.getScore(pet) <= 1) {
		warn = `§l[§c$PET IS HUNGRY!§r§l]§r`
	}
	const health = pet.getComponent('minecraft:health')
	const mode = pet.getProperty('tp_pw:mode')
	const form = new ActionFormData()
		.title(`§l§5[§1${petList[chosenPet]}§f§5§l]§r §l§2Level Stats`)
		.body(`
§a§l${pet.nameTag}§r §a§lLevel Info§r \n
    §6HEALTH: ${healthDisplayer(pet)}§r
    §6HUNGER: §e${hungerDisplayer(pet)}§r
    §6LVL: §e${petLVL.getScore(pet)}§r
    §6EXP: §e${petEXP.getScore(pet)}§r/§e${(defaultEXP * (petLVL.getScore(pet)))*0.8}§r
    §6MODE: ${modeDisplayer(mode)}§r\n
    §bLocation:
        §ax: ${Math.floor(pet.location.x)}
        y: ${Math.floor(pet.location.y)}
        z: ${Math.floor(pet.location.z)}§r\n
    ${warn}
`)
		.button('§l§1Teleport Pet')
		.button('§l§1Mode')
		.button('§l§2Back')
		.button('§l§4Close')
	form.show(player).then((r=ActionFormResponse)=>{
		if (r.selection === 0) {
			pet.teleport(player.location)
		} else if (r.selection === 1) {
			petModeOption(player, pet, true)
		} else if (r.selection === 2) {
			quickOption ? null : newPetLevelHUD(player)
		}
	})
}
function petModeOption(player, pet, quickOption = false) {
    const form = new ActionFormData()
		.title(`Pet Mode`)
		.body(`
§a§l${pet.nameTag}§r Choose Mode
`)
		.button('§l§dPassive')
		.button('§l§2Neutral')
		.button('§l§4Aggressive')
		.button({ translate: "settings.tp_pw.back.button" }, "textures/tp/pw/settings/back")
	form.show(player).then((r=ActionFormResponse)=>{
		if (r.selection === 0) {
            pet.triggerEvent('tp_pw:passive_mode')
            player.runCommand('title @s actionbar Changing to passive')
            system.runTimeout(()=>{
                quickOption ? showPetInfoHUD(player, pet, true) : showPetInfoHUD(player, pet)
            },1*20)
		} else if (r.selection === 1) {
            pet.triggerEvent('tp_pw:neutral_mode')
            player.runCommand('title @s actionbar Changing to neutral')
            system.runTimeout(()=>{
                quickOption ? showPetInfoHUD(player, pet, true) : showPetInfoHUD(player, pet)
            },1*20)
		} else if (r.selection === 2) {
            pet.triggerEvent('tp_pw:aggressive_mode')
            player.runCommand('title @s actionbar Changing to aggressive')
            system.runTimeout(()=>{
                quickOption ? showPetInfoHUD(player, pet, true) : showPetInfoHUD(player, pet)
            },1*20)
		} else if (r.selection === 3) {
            quickOption ? showPetInfoHUD(player, pet, true) : showPetInfoHUD(player, pet)
		}
	})
}
function defaultMode(pet){
	let mode = null
	switch (pet.getProperty('tp_pw:mode')) {
		case 'neutral':
			mode = 0
			break;
		case 'passive':
			mode = 1
			break;
		case 'aggressive':
			mode = 2
			break;
	}
	return mode;
}
function settingsHUD(player) {
	const defaultDifficulty = world.getDynamicProperty('tp_pw:settings_diff')
	const defaultVolume = player.getDynamicProperty('tp_pw:settings_volume')
	const defaultCamera = player.getDynamicProperty('tp_pw:settings_camera')
	const difficulty = [
		'Easy',
		'Normal',
		'Hard'
	]
	new ModalFormData()
		.title(`Pet Weapons Settings`)
		.toggle(`Master Volume`, defaultVolume)
		.toggle(`Cinematic Camera`, defaultCamera)
		.dropdown(`Pet Difficulty`, difficulty, defaultDifficulty)
		.show(player)
		.then((r) => {
			if (r.formValues[0] == true) {
				player.setDynamicProperty('tp_pw:settings_volume', true)
			} else if (r.formValues[0] == false) {
				player.setDynamicProperty('tp_pw:settings_volume', false)
			}

			if (r.formValues[1] == true) {
				player.setDynamicProperty('tp_pw:settings_camera', true)
			} else if (r.formValues[1] == false) {
				player.setDynamicProperty('tp_pw:settings_camera', false)
			}

			if (r.formValues[2] == 0) {
				world.setDynamicProperty('tp_pw:settings_diff', 0)
			} else if (r.formValues[2] == 1) {
				world.setDynamicProperty('tp_pw:settings_diff', 1)
			} else if (r.formValues[2] == 2) {
				world.setDynamicProperty('tp_pw:settings_diff', 2)
			}
		})
}
function resetLevel() {
    console.warn('masuk')
    world.getPlayers().forEach(player=>{
		weapons.forEach(weapon=>{
			player.runCommand(`scoreboard players set @s tp_pw:${weapon}_CD 0`)
			player.runCommand(`scoreboard players set @s tp_pw:${weapon}_LVL 1`)
			player.runCommand(`scoreboard players set @s tp_pw:${weapon}_EXP 0`)
			player.runCommand(`scoreboard players set @s tp_pw:${weapon}_ULT 0`)
		})
    })
}
world.afterEvents.itemUse.subscribe((arg) => {
	const item = arg.itemStack
	const player = arg.source
	if (item.typeId === `tp_pw:configurations`) {
		mainMenu(player)
	}
    if (item.typeId==='tp_pw:auto.tamer') {
        autoTamerMenu(player)
    }
})
function autoTamerMenu(player) {
    const slot = player.selectedSlotIndex

    player.playSound("item.book.page_turn", { pitch: 1.0, volume: 1.0 })
    instanceMenu(

        player,
        { translate: "settings.tp_pw.auto_tamer.title"},
        { translate: "settings.tp_pw.auto_tamer.body"},
        [
			{
                text: "Feral Lynx",
                image: "textures/tp/pw/settings/pets/0",
                command: () => {
                    player.playSound("item.book.page_turn", { pitch: 1.0, volume: 1.0 })
                    const inventory = player.getComponent("minecraft:inventory");
                    inventory.container.setItem(slot, new ItemStack(`tp_pw:feral_lynx.tamer`));
                }
            },
            {
                text: "Flame Hawk",
                image: "textures/tp/pw/settings/pets/2",
                command: () => {
                    player.playSound("item.book.page_turn", { pitch: 1.0, volume: 1.0 })
                    const inventory = player.getComponent("minecraft:inventory");
                    inventory.container.setItem(slot, new ItemStack(`tp_pw:flame_hawk.tamer`));
                }
            },
            {
                text: "Frost Fox",
                image: "textures/tp/pw/settings/pets/1",
                command: () => {
                    player.playSound("item.book.page_turn", { pitch: 1.0, volume: 1.0 })
                    const inventory = player.getComponent("minecraft:inventory");
                    inventory.container.setItem(slot, new ItemStack(`tp_pw:frost_fox.tamer`));
                }
            },
            {
                text: "Storm Griffin",
                image: "textures/tp/pw/settings/pets/5",
                command: () => {
                    player.playSound("item.book.page_turn", { pitch: 1.0, volume: 1.0 })
                    const inventory = player.getComponent("minecraft:inventory");
                    inventory.container.setItem(slot, new ItemStack(`tp_pw:storm_griffin.tamer`));
                }
            },
            {
                text: "Nebula Dragon",
                image: "textures/tp/pw/settings/pets/4",
                command: () => {
                    player.playSound("item.book.page_turn", { pitch: 1.0, volume: 1.0 })
                    const inventory = player.getComponent("minecraft:inventory");
                    inventory.container.setItem(slot, new ItemStack(`tp_pw:nebula_dragon.tamer`));
                }
            },
            {
                text: "Music Golem",
                image: "textures/tp/pw/settings/pets/3",
                command: () => {
                    player.playSound("item.book.page_turn", { pitch: 1.0, volume: 1.0 })
                    const inventory = player.getComponent("minecraft:inventory");
                    inventory.container.setItem(slot, new ItemStack(`tp_pw:music_golem.tamer`));
                }
            }
        ]
    )
}
//Utilities
function instanceMenu(player, title, body, buttons) {
    const UI = new ActionFormData()
    .title(title)
    .body(body)
    buttons.forEach(button => {
        button.image
        ? UI.button(button.text, button.image)
        : UI.button(button.text)
    })
    UI.show(player).then(result => {
        buttons.forEach((button, index) => {
            if (result.selection === index) {
                button.command(player)
            }
        })
    })
    return UI
}
function getItemOnInventory(player, item) {

    /** @type { EntityInventoryComponent } */
    const inventory = player.getComponent("minecraft:inventory")
    for (let i = 0; i < inventory.container?.size; i++) {

        if (!inventory.container.getItem(i)) { continue }

        const itemI = inventory.container.getItem(i)
        
        if (itemI.typeId === item) {

            return itemI;

            
        }

    }
    return false



}
const weapons = [	'blade_of_the_wild',	'celestial_gauntlets',	'ember_bow',	'glacier_staff',	'mystic_flute',	'thunder_mace']
world.afterEvents.playerInteractWithEntity.subscribe(arg => {
    const player = arg.player
    const target = arg.target
    if(petsId.includes(target.typeId)) {
        try {
        } catch (error) {}
        
            if(target.hasTag(`tp_pw:${player.id}`)){
                if(getItemMainHand(player)?.typeId != target.typeId+`.food` && player.isSneaking) {
                    showPetInfoHUD(player, target, true)
                }
            }
    }
})
function checkItemInMainHand(player, itemId) {
    if (player.getComponent("equippable")?.getEquipment("Mainhand")?.typeId === itemId) {
        return true
    } else {
        return false
    }
}
function getItemMainHand(player) {
    return player.getComponent("equippable")?.getEquipment("Mainhand");
}
}