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

// Animal Data

const subcategory = new Map([
    ["babirusa", ["Charge"]],
    ["bear", ["Looting"]],
    ["black_bear", ["Looting"]],
    ["black_panther", ["Night Vision"]],
    ["bufallo", ["Resistance"]],
    ["bull", ["Strength"]],
    ["capybara", ["Gather"]],
    ["caracal", ["Night Vision"]],
    ["cheetah", ["Speed"]],
    ["dingo", ["Looting"]],
    ["elephant", ["Storage"]],
    ["eurasian_lynx", ["Night Vision"]],
    ["forest_buffalo", ["Resistance"]],
    ["gaur", ["Strength"]],
    ["gorilla", ["Gather"]],
    ["hippo", ["Regeneration"]],
    ["leopard", ["Looting"]],
    ["lion", ["Looting", "Charge"]],
    ["lowland_tapir", ["Charge"]],
    ["musk_ox", ["Storage"]],
    ["paca", ["Haste"]],
    ["panda", ["Gather"]],
    ["polar_bear", ["Looting"]],
    ["puma", ["Jump Boost"]],
    ["rhinoceros", ["Charge"]],
    ["snow_leopard", ["Jump Boost"]],
    ["takin", ["Charge"]],
    ["tiger", ["Looting", "Charge"]],
    ["visayan_warty_pig", ["Haste"]],
    ["white_rhinoceros", ["Charge"]],
    ["white_tiger", ["Looting"]],
    ["wild_boar", ["Charge"]],
    ["capra_ibex", ["Jump Boost"]],
    ["chinese_water_deer", ["Regeneration"]],
    ["deer", ["Regeneration"]],
    ["donkey", ["Storage"]],
    ["dromedary_camel", ["Storage"]],
    ["gazelle", ["Speed"]],
    ["gerenuk", ["Speed"]],
    ["giraffe", ["Fortune"]],
    ["guanaco", ["Fortune"]],
    ["ibex", ["Fortune"]],
    ["kudu", ["Fortune"]],
    ["llama", ["Storage"]],
    ["moose", ["Looting", "Charge"]],
    ["mountain_goat", ["Looting", "Charge"]],
    ["nilgiri_tahr", ["Fortune"]],
    ["onager", ["Fortune"]],
    ["pronghorn", ["Speed"]],
    ["przewalskis_horse", ["Fortune"]],
    ["scimitar_horned_oryx", ["Looting", "Charge"]],
    ["zebra", ["Fortune"]],
    ["european_rabbit", ["Fortune"]],
    ["red_kangaroo", ["Storage"]],
    ["rock_wallaby", ["Jump Boost"]],
    ["tree_kangaroo", ["Storage"]],
    ["crocodile", ["Looting", "Water Breathing"]],
    ["indian_gharial", ["Water Breathing"]],
    ["komodo", ["Charge"]],
    ["tortoise", ["Resistance"]],
    ["african_civet", ["Fortune"]],
    ["bat_eared_fox", ["Gather"]],
    ["beaver", ["Haste"]],
    ["binturong", ["Fortune"]],
    ["coati", ["Fortune"]],
    ["fennec_fox", ["Night Vision"]],
    ["fox", ["Gather"]],
    ["giant_anteater", ["Ranged", "Fortune"]],
    ["honey_badger", ["Fortune"]],
    ["hyena", ["Looting"]],
    ["jackal", ["Looting"]],
    ["maned_wolf", ["Looting"]],
    ["racoon", ["Gather"]],
    ["red_panda", ["Fortune"]],
    ["wolf", ["Looting"]],
]);

const assault_animals = [
    {id: 'babirusa'},
    {id: 'lion'},
    {id: 'lowland_tapir'},
    {id: 'rhinoceros'},
    {id: 'takin'},
    {id: 'tiger'},
    {id: 'white_rhinoceros'},
    {id: 'wild_boar'},
    {id: 'llama'},
    {id: 'moose'},
    {id: 'mountain_goat'},
    {id: 'scimitar_horned_oryx'},
    {id: 'komodo'},
    {id: 'bear'},
    {id: 'black_bear'},
    {id: 'giant_anteater'}
];

const utility_animals = [
    {id: 'capybara'},
    {id: 'dingo'},
    {id: 'elephant'},
    {id: 'gorilla'},
    {id: 'leopard'},
    {id: 'musk_ox'},
    {id: 'panda'},
    {id: 'polar_bear'},
    {id: 'white_tiger'},
    {id: 'donkey'},
    {id: 'dromedary_camel'},
    {id: 'red_kangaroo'},
    {id: 'tree_kangaroo'},
    {id: 'bat_eared_fox'},
    {id: 'fox'},
    {id: 'hyena'},
    {id: 'jackal'},
    {id: 'maned_wolf'},
    {id: 'racoon'},
    {id: 'wolf'}
];

const support_animals = [
    {id: 'black_panther'},
    {id: 'buffalo'},
    {id: 'bull'},
    {id: 'caracal'},
    {id: 'cheetah'},
    {id: 'eurasian_lynx'},
    {id: 'forest_buffalo'},
    {id: 'gaur'},
    {id: 'hippo'},
    {id: 'paca'},
    {id: 'puma'},
    {id: 'snow_leopard'},
    {id: 'visayan_warty_pig'},
    {id: 'capra_ibex'},
    {id: 'chinese_water_deer'},
    {id: 'deer'},
    {id: 'gazelle'},
    {id: 'gerenuk'},
    {id: 'pronghorn'},
    {id: 'rock_wallaby'},
    {id: 'crocodile'},
    {id: 'indian_gharial'},
    {id: 'tortoise'},
    {id: 'beaver'},
    {id: 'fennec_fox'}
];

const availableItems = [
  "candy_blue",
  "candy_green",
  "candy_red",
  "pet_coin",
  "toy_ball",
  "toy_bone",
  "toy_coil",
  "whistle",
  "pet_bed",
  "addon_book"
]

world.beforeEvents.itemUse.subscribe(data => {
    if (data.itemStack.typeId !== "md_bap:addon_book") return;
    let player = data.source // This makes sure the player is data.source from now on in the code.
    let pet = player.getEntitiesFromViewDirection({maxDistance: 5}).filter(e => e.entity.typeId.includes("md_bap:"))[0];
    if (pet) {
      system.run(() => showAnimalMenu(player, pet.entity.typeId.split(":")[1]))
    } else {
      system.run(() => main(player))      
    }    
})
let title = "§l§0Baby Animals Add-On"
function main(player) {
    const form = new ActionFormData()
    .title(title)
    .body(`Welcome §l${player.nameTag}§r!\nWelcome to Baby Animals!\n\nThis Add-On adds 75 little animal friends to your world, spawning in all types of biomes. Each animal has it's own unique skill or ability to help. Please select a button to find out more.\n\nPlease select a category`)
    .button('§lSUPPORT\n§rLittle supporters', "textures/maca/bap/gui/rock_wallaby")
    .button('§lASSAULT\n§rLittle fighters', "textures/maca/bap/gui/lion")
    .button('§lUTILITY\n§rLittle helpers', "textures/maca/bap/gui/dromedary_camel")
    .button('§lItems\n§rCustom items', "textures/maca/bap/items/pet_coin")
    .button('§lCONTACT\n§rReach out!', "textures/gui/newgui/Friends")
    .show(player).then(r => { 
        if (r.selection == 0) {
            system.run(() => category(`support`, player))
        }
        if (r.selection == 1) {
            system.run(() => category('assault', player))
        }
        if (r.selection == 2) {
            system.run(() => category('utility', player))
        }
        if (r.selection == 3) {
          system.run(() => items(player))
        }
        if (r.selection == 4) {
            system.run(() => contact(player))
        }

})
}

function contact(player) {
    const form = new ActionFormData()
    form.title('Contact')
    form.body('Contact E-Mail: §lmacadesigns@outlook.com\n\n§rDiscord: discord.gg/GAXE85Y9R5')
    form.button('Back', "textures/gui/controls/left")
    form.show(player).then(r => { 
        if (r.selection == 0) {
            system.run(() => main(player))
        }
    })
}

function category(type, player) {
    let counter = 0
    const form = new ActionFormData()
    form.title(`${type}.md_bap.menu.title`)
    for (let animal of getCategory(type)) {
       form.button(animal.id + '.md_bap.menu.title', "textures/maca/bap/gui/" + animal.id)
       counter ++
    }
    form.button('Back', "textures/gui/controls/left")
    form.show(player).then(r => { 
        if (r.selection === counter) {
            system.run(() => main(player))
        }
        else {
          const animal = getCategory(type)[r.selection]
          showAnimalMenu(player, animal.id)
        }

}).catch(e => {
    console.error(e, e.stack)
})
}

function getCategory(type) {
    if (type === 'support') return support_animals
    if (type === 'assault') return assault_animals  
    if (type === 'utility') return utility_animals
}

// List of custom items page
function items(player) {
  const form = new ActionFormData()
  .title(`Custom Pet Items`)
  .body(`items.md_bap.menu.description`)
  for (const item of availableItems) {
    form.button(item + '.md_bap.menu.title', "textures/maca/bap/items/" + item);
  }
  form.button('Back', "textures/gui/controls/left")

  form.show(player).then(r => {
    if (r.selection === 0) {
      system.run(() => itemMenu(player, `candy_blue`))
    }
    if (r.selection === availableItems.length) {
      system.run(() => main(player))
    }
    else if (r.selection) {
      const selection = availableItems[r.selection];
      system.run(() => itemMenu(player, selection))
    }    
  })
}

function itemMenu(player, id) {
  const form = new ActionFormData()
  .title(id + `.md_bap.menu.title`)
  .body(id + `.md_bap.menu.description`)
  .button('Back', "textures/gui/controls/left")

  form.show(player).then(r => {
    if (r.selection === 0) {
      items(player)
    }
  })
}

// General Animal Page Function
function showAnimalMenu(player, id) {
    const abilities = subcategory.get(id);
    let button = "";
  
    if (abilities && abilities.length > 0) {
      button = `${abilities[0]}`;
      if (abilities.length > 1) {
        for (let i = 1; i < abilities.length; i++) {
          button += ` & ${abilities[i]}`;
        }
      }
    } else {
      button = "Unknown Ability";
    }
    const form = new ActionFormData()
    .title(`${id}.md_bap.menu.title`)
    .body(`${id}.md_bap.menu.description`)
    .button(`Special Ability: ${button}`, `textures/maca/bap/gui/${id}`)
    .button(`Fun Facts!`, `textures/maca/bap/gui/${id}`)
    .button('Back', "textures/gui/controls/left")
  
    form.show(player).then(r => {
      if (r.cancelled) return

      if (r.selection === 0) {
        showAnimalAbilityMenu(player, id)
      }
  
      if (r.selection === 1) {
        showAnimalFactMenu(player, id)
      }

      if (r.selection === 2) {
        main(player)
      }
    })
  }

  function showAnimalFactMenu(player, id) {
    const form = new ActionFormData()
    .title(`${id}.md_bap.menu.title`)
    .body(`${id}.md_bap.menu.fun_fact`)
    .button('Back', "textures/gui/controls/left")
  
    form.show(player).then(r => {
      if (r.cancelled) return
  
      if (r.selection === 0) {
        showAnimalMenu(player, id)
      }
    })
  }
  
  function showAnimalAbilityMenu(player, id) {
    const abilities = subcategory.get(id);
    let title = "";
    let description = "";
  
    if (abilities && abilities.length > 0) {
      title = `${abilities[0]}.md_bap.menu.title`;
      description = `${abilities[0]}.md_bap.menu.description`;
  
      // Handle the case where there are multiple abilities (like the lion)
      if (abilities.length > 1) {
        description = `${id}.ability.md_bap.menu.description`;
        title = `${id}.ability.md_bap.menu.title`;
      }
    } else {
      showAnimalMenu(player, id);
    }
  
    const form = new ActionFormData()
      .title(title)
      .body(description)
      .button('Back', "textures/gui/controls/left");
  
    form.show(player).then(r => {
      if (r.cancelled) return;
  
      if (r.selection === 0) {
        showAnimalMenu(player, id);
      }
    });
  }