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

const tags = {
  "Basic Arms": "new_arm1",
  "Basic Arms + Watch": "new_arm2",
  "Yellow Arms": "new_arm3",
  "Arms with Gloves": "new_arm4",
  "Arms with Lace-Up Gloves": "new_arm5"
}
const player_menu = new ItemStack('ks_pa:player_menu_item', 1);

world.afterEvents.playerSpawn.subscribe(({ player }) => {
  if (!player.hasTag('ks_pa_initialized')){
    player.setDynamicProperty("ks_pa:timer", 0);
    player.setDynamicProperty("ks_pa:initiate_call", false);
    player.setDynamicProperty("ks_pa:loop_idle", false);
    player.setDynamicProperty("ks_pa:loop_idle_event", false);
    player.setDynamicProperty("ks_pa:idle_event_delay", 0);
    player.setDynamicProperty("ks_pa:finish_idle_event", false);
    player.setDynamicProperty("ks_pa:loop_idle_sword", false);
    player.setDynamicProperty("ks_pa:loop_idle_low_health", false);
    player.setDynamicProperty("ks_pa:loop_walk", false);
    player.setDynamicProperty("ks_pa:loop_walk_sword", false);
    player.setDynamicProperty("ks_pa:loop_walk_low_health", false);
    player.setDynamicProperty("ks_pa:loop_sprint", false);
    player.setDynamicProperty("ks_pa:loop_sprint_sword", false);
    player.setDynamicProperty("ks_pa:loop_sprint_low_health", false);
    player.setDynamicProperty("ks_pa:loop_sneak_still", false);
    player.setDynamicProperty("ks_pa:loop_sneak", false);
    player.setDynamicProperty("ks_pa:loop_climb", false);
    player.setDynamicProperty("ks_pa:loop_climb_still", false);
    player.setDynamicProperty("ks_pa:loop_jump", false);
    player.setDynamicProperty("ks_pa:loop_fall", false);
    player.setDynamicProperty("ks_pa:loop_land", false);
    player.setDynamicProperty("ks_pa:loop_fly_still", false);
    player.setDynamicProperty("ks_pa:loop_fly", false);
    player.setDynamicProperty("ks_pa:loop_fast_fly", false);
    player.setDynamicProperty("ks_pa:loop_swim_still", false);
    player.setDynamicProperty("ks_pa:loop_swim", false);
    player.setDynamicProperty("ks_pa:loop_crawl_still", false);
    player.setDynamicProperty("ks_pa:loop_crawl", false);
    player.setDynamicProperty("ks_pa:loop_ride_minecart", false);
    player.setDynamicProperty("ks_pa:loop_ride_minecart_move", false);
    player.setDynamicProperty("ks_pa:test_hold_sword", false);
    player.setDynamicProperty("ks_pa:test_player_velocity", 0);
    player.setDynamicProperty("ks_pa:can_crawl", false);
  }
  player.setDynamicProperty("ks_pa:changed", false);
  if (!world.getDynamicProperty("ks_pa:firstSpawn")) {
    world.setDynamicProperty("ks_pa:enableAll", true);
    world.setDynamicProperty("ks_pa:disablePlayers", "");
    world.setDynamicProperty("ks_pa:enablePlayers", "");
  }
  if (!player.hasTag("new_arm1") && !player.hasTag("new_arm2") && !player.hasTag("new_arm3") && !player.hasTag("new_arm4") && !player.hasTag("new_arm5")) {
    player.addTag("new_arm1");
    player.runCommand('give @s ks_pa:player_menu_item')
    player.setDynamicProperty("ks_pa:first", true);
    player.setDynamicProperty("ks_pa:third", true);
    player.setDynamicProperty("ks_pa:idle_sword_animation", true);
    player.setDynamicProperty("ks_pa:attack_animations", true);
    player.setDynamicProperty("ks_pa:idle_animation", true);
    player.setDynamicProperty("ks_pa:walk_animation", true);
    player.setDynamicProperty("ks_pa:sprint_animation", true);
    player.setDynamicProperty("ks_pa:low_health_animation", true);
    player.setDynamicProperty("ks_pa:minecart_animation", true);
    player.setDynamicProperty("ks_pa:jump_animation", true);
    player.setDynamicProperty("ks_pa:land_animation", true);
    player.setDynamicProperty("ks_pa:fly_animation", true);
    player.setDynamicProperty("ks_pa:climb_animation", true);
    player.setDynamicProperty("ks_pa:fall_animation", true);
    player.setDynamicProperty("ks_pa:sneak_animation", true);
    player.setDynamicProperty("ks_pa:swim_animation", true);
    player.setDynamicProperty("ks_pa:crawl_animation", true);
    player.setDynamicProperty("ks_pa:stretch_animation", true);
    world.setDynamicProperty("ks_pa:firstSpawn", true);
  }
  player.addTag('ks_pa_initialized');
})

async function forceShow(player, form, timeout = 100) {
  const startTick = system.currentTick

  while ((system.currentTick - startTick) < timeout) {
    const response = await form.show(player)

    if (response.cancelationReason !== "UserBusy") return response
  }
}

async function skinChangeMenu(player) {
  const form = new ActionFormData()
  form.title("§l§5Arm Styles")
  form.body("Which §b§larm style§r should your player wear?\n\n")

  const tagNames = Object.keys(tags)

  // Add tag buttons
  for (const tagName of tagNames) {
    const tagId = tags[tagName]
    form.button(tagName, "textures/ks/pa/menu/button_icon/" + tagId)
  }

  // Add "Back" button at the end
  form.button("Back")

  const response = await forceShow(player, form)
  if (response.canceled) return

  // Check if the "Back" button was clicked
  if (response.selection === tagNames.length) {
    return settings(player) // Replace with your actual back function
  }

  // Apply selected tag
  const selectedTag = Object.values(tags)[response.selection]
  if (selectedTag) {
    for (const tag of Object.values(tags)) {
      if (tag !== selectedTag && player.hasTag(tag)) {
        player.removeTag(tag)
      }
    }
    player.addTag(selectedTag)
  }
}

function settings(player) {
  const form = new ActionFormData()
  form.title("§l§5Player Animations Add-On")
  form.button("Introduction", "textures/ks/pa/menu/button_icon/intro")
  form.button("Arm Styles", "textures/ks/pa/menu/button_icon/skin")
  form.button("General Settings", "textures/ks/pa/menu/button_icon/general")
  form.button("Individual Animation Toggles", "textures/ks/pa/menu/button_icon/indiv_anims")
  form.button("Animations Guide", "textures/ks/pa/menu/button_icon/guide")
  form.button("Support", "textures/ks/pa/menu/button_icon/support")
  form.button("Dynamic Camera Settings", "textures/ks/pa/menu/button_icon/camera")
  form.button("Player Animation Toggles", "textures/ks/pa/menu/button_icon/admin")
  form.show(player).then((result) => {
    if (result.canceled) return;
    if (result.selection === 0) {
      introMenu(player);
    } else if (result.selection === 1) {
      skinChangeMenu(player);
    } else if (result.selection === 2) {
      generalSettings(player);
    } else if (result.selection === 3) {
      animationSettings(player);
    } else if (result.selection === 4) {
      howToGuide(player);
    } else if (result.selection === 5) {
      support(player);
    } else if (result.selection === 6) {
      cameraMenu(player);
    } else if (result.selection === 7) {
      adminControls(player);
    }
  })
}

function introMenu(player) {
  const introMenu = new ActionFormData()
  introMenu.title("§l§5Introduction")
  introMenu.body(" Welcome to the §dPlayer Animations Add-On§r by §cKreatik Studios§r!\nThis Add-On gives your Minecraft character §bawesome new animations§r to make everything feel more alive and fun. Whether you're walking, sprinting, swimming, jumping, or just standing still - your character will now move in cooler, more realistic ways!\n\n§b§l What You Can Do:\n§r§l■ Animations for Every Action!§r\n§rYour character now moves differently when doing things like:\n§7- Walking, sprinting, sneaking, crawling\n- Swimming, flying, climbing, falling, riding a minecart\n- Holding a sword or having low health\n- Jumping and landing\n- And more!\n\n§r§l■ Easy-to-Use Settings Menu§r\n§rIn the menu, you can:\n§7- Turn on or off any animation you want\n- Turn them all off or on at once\n- Try different settings to see what you like best!\n\n§r§l■ Custom Dynamic Camera§r\n§rChoose from §b6 different camera angles§r to get the perfect third person view!\n\n§r§l■ Cool First-Person Arm Styles§r\n§rWhile swimming, climbing, or doing other actions in first person, you'll see §bcustom arms§r! Pick your favorite from §b5 unique styles§r.\n\n§r§l■ Learn About Every Animation§r\n§rTap the §dAnimations Guide button§r in the menu to learn what each animation does and when it happens.\n\n§bHave fun experimenting with all the animations and camera angles - make your character move your way!");
  introMenu.button("Back");
  introMenu.show(player).then((result) => {
    if (result.canceled) return;
    settings(player);
  });
}

function cameraMenu(player) {
  const form = new ActionFormData();
  form.title("§l§5Dynamic Camera Settings");
  form.button("Default", "textures/ks/pa/menu/camera/default");
  form.button("Front View", "textures/ks/pa/menu/camera/front");
  form.button("Left View", "textures/ks/pa/menu/camera/left");
  form.button("Right View", "textures/ks/pa/menu/camera/right");
  form.button("Top View", "textures/ks/pa/menu/camera/top");
  form.button("Over The Left Shoulder View", "textures/ks/pa/menu/camera/shoulder_left");
  form.button("Over The Right Shoulder View", "textures/ks/pa/menu/camera/shoulder_right");
  form.button("Back");
  form.show(player).then((result) => {
    if (result.canceled) return;

    let selectedAngle = "";
    switch (result.selection) {
      case 0:
        selectedAngle = "back";
        break;
      case 1:
        selectedAngle = "front";
        break;
      case 2:
        selectedAngle = "left";
        break;
      case 3:
        selectedAngle = "right";
        break;
      case 4:
        selectedAngle = "top";
        break;
      case 5:
        selectedAngle = "shoulder_left";
        break;
      case 6:
        selectedAngle = "shoulder_right";
        break;
      case 7:
        settings(player);
        break;
    }

    // Guardar el ángulo seleccionado en una propiedad dinámica
    player.setDynamicProperty("ks_pa:angle", selectedAngle);
  });
}

function support(player) {
  const support = new ActionFormData()
  support.title("§l§5Support")
  support.body("If you have any §l§bquestions§r, §l§bencounter any issues§r, or simply §l§bwish to get in touch§r, please feel free to reach out using one of the contact options below. Whether it's a quick §bmessage via Discord§r or a more detailed §binquiry by email§r, our team will respond as promptly as possible.\n\n§b§lDiscord§r: §cKreatik Studios§r Community Server (§bLink§r: discord.gg/2tY9NEmA2F)\n\n§b§lEmail§r: contact@kreatikstudios.com");
  support.button("Back");
  support.show(player).then((result) => {
    if (result.canceled) return;
    settings(player);
  });
}

function howToGuide(player) {
  const messages = [
    "§b§lIdle Animation§r - Plays in both 1st and 3rd person views when you're §bstanding still§r, waiting for the next move.",
    "§b§lIdle Sword Animation§r - Plays when you're §bstanding still with a sword§r, ready for battle.",
    "§b§lIdle Low Health Animation§r - Plays when you're §bstanding still while having less than half of your health§r.",
    "§b§lWalking Animation§r - Plays in both 1st and 3rd person views when you're §bwalking around normally§r.",
    "§b§lWalking Sword Animation§r - Plays when you're §bwalking around while holding a sword§r, ready to deal some damage!",
    "§b§lWalking Low Health Animation§r - Plays when you §bwalk while hurt§r, moving a bit slower.",
    "§b§lSprinting Animation§r - Plays in both 1st and 3rd person views when you §brun super fast§r - zoom zoom!",
    "§b§lSprinting Sword Animation§r - Plays when you §brun while holding a sword§r like a hero.",
    "§b§lSprinting Low Health Animation§r - Plays when you're §bhurt but still running§r to safety!",
    "§b§lJump Animation§r - Plays in both 1st and 3rd person views every time you §bjump§r into the air - boing!",
    "§b§lFalling Animation§r - Plays when you're §bfalling§r from up high - uh oh!",
    "§b§lClimbing Animation§r - Plays in both 1st and 3rd person views when you're §bclimbing ladders or vines§r like a real adventurer.",
    "§b§lLanding Animation§r - Plays in both 1st and 3rd person views when you §bhit the ground§r after jumping or falling - stick the landing!",
    "§b§lSneaking Still Animation§r - Plays when you're §bcrouching in place§r without moving, staying hidden.",
    "§b§lSneaking Animation§r - Plays when you §bcrouch and sneak§r around like a spy.",
    "§b§lSwimming Still Animation§r - Plays in both 1st and 3rd person views when you're §bfloating in water§r without moving, like a lazy river ride.",
    "§b§lSwimming Animation§r - Plays in both 1st and 3rd person views when you're §bswimming around§r in the water - splash splash!",
    "§b§lCrawling Still Animation§r - Plays in both 1st and 3rd person views when you're §blying down and staying still§r, nice and quiet.",
    "§b§lCrawling Animation§r - Plays in both 1st and 3rd person views when you're §bcrawling forward§r on your belly like a sneaky pro.",
    "§b§lFlying Still Animation§r - Plays when you're §bflying§r in the air but not moving.",
    "§b§lFlying Animation§r - Plays when you're §bsoaring through the sky§r like a superhero!",
    "§b§lFast Flying Animation§r - Plays when you're §bflying super fast§r through the sky - whoosh!",
    "§b§lAttack & Mine Animations§r - Plays when you §bpunch§r with your hands while holding any kind of sword or pickaxe - smack!",
    "§b§lRiding Idle Minecart Animation§r - Plays in both 1st and 3rd person views when you're §bsitting still in a minecart§r, enjoying the ride.",
    "§b§lRiding Moving Minecart Animation§r - Plays in both 1st and 3rd person views when you're §briding a moving minecart§r, speeding down the tracks!",
    "§b§lStretching Animation§r - Plays when your player takes a moment to §bstretch out§r after being still for a while."
  ];

  const form = new ActionFormData()
    .title("§l§5Animations Guide")
    .body(messages.join("\n\n"))
    .button("Back");

  form.show(player).then((result) => {
    if (result.canceled) return;
    settings(player);
  });
}

function generalSettings(player) {
  const settings = new ModalFormData()
  settings.title("§l§5General Settings")
  settings.toggle("Enable Custom §l§bFirst Person§r Animations", player.getDynamicProperty("ks_pa:first"))
  settings.toggle("Enable Custom §b§lThird Person§r Animations", player.getDynamicProperty("ks_pa:third"))
  settings.toggle("Custom Dynamic Camera", player.getDynamicProperty("ks_pa:camera"))
  settings.show(player).then((result) => {
    if (result.canceled) return;
    let [first, third, camera] = result.formValues;
    player.setDynamicProperty("ks_pa:first", first);
    player.setDynamicProperty("ks_pa:third", third);
    player.setDynamicProperty("ks_pa:camera", camera);
    player.setDynamicProperty("ks_pa:changed", true);
  });
}

function animationSettings(player) {
  const settings = new ModalFormData()
  settings.title("§l§5Individual Animation Toggles")
  settings.toggle("Custom §b§lStand§r Animation", player.getDynamicProperty("ks_pa:idle_animation"))
  settings.toggle("Custom §b§lWalk§r Animation", player.getDynamicProperty("ks_pa:walk_animation"))
  settings.toggle("Custom §b§lSprint§r Animation", player.getDynamicProperty("ks_pa:sprint_animation"))
  settings.toggle("Custom §b§lJump§r Animation", player.getDynamicProperty("ks_pa:jump_animation"))
  settings.toggle("Custom §b§lLand§r Animation", player.getDynamicProperty("ks_pa:land_animation"))
  settings.toggle("Custom §b§lFly§r Animations", player.getDynamicProperty("ks_pa:fly_animation"))
  settings.toggle("Custom §b§lClimb§r Animations", player.getDynamicProperty("ks_pa:climb_animation"))
  settings.toggle("Custom §b§lFall§r Animation", player.getDynamicProperty("ks_pa:fall_animation"))
  settings.toggle("Custom §b§lSneak§r Animations", player.getDynamicProperty("ks_pa:sneak_animation"))
  settings.toggle("Custom §b§lSwim§r Animations", player.getDynamicProperty("ks_pa:swim_animation"))
  settings.toggle("Custom §b§lCrawl§r Animations", player.getDynamicProperty("ks_pa:crawl_animation"))
  settings.toggle("Custom §b§lLow Health§r Animations", player.getDynamicProperty("ks_pa:low_health_animation"))
  settings.toggle("Custom §b§lSword Handling§r Animations", player.getDynamicProperty("ks_pa:idle_sword_animation"))
  settings.toggle("Custom §b§lAttack & Mine§r Animations", player.getDynamicProperty("ks_pa:attack_animations"))
  settings.toggle("Custom §b§lMinecart§r Animations", player.getDynamicProperty("ks_pa:minecart_animation"))
  settings.toggle("Custom §b§lStretch§r Animation", player.getDynamicProperty("ks_pa:stretch_animation"))
  settings.show(player).then((result) => {
    if (result.canceled) return;
    let [idleAnim, walkAnim, sprintAnim, jumpAnim, landAnim, flyAnim, climbAnim, fallAnim, sneakAnim, swimAnim, crawlAnim, healthAnim, idleSwordAnim, attackAnim, minecartAnim, stretchAnim ] = result.formValues;
    player.setDynamicProperty("ks_pa:idle_animation", idleAnim);
    player.setDynamicProperty("ks_pa:walk_animation", walkAnim);
    player.setDynamicProperty("ks_pa:sprint_animation", sprintAnim);
    player.setDynamicProperty("ks_pa:jump_animation", jumpAnim);
    player.setDynamicProperty("ks_pa:land_animation", landAnim);
    player.setDynamicProperty("ks_pa:fly_animation", flyAnim);
    player.setDynamicProperty("ks_pa:climb_animation", climbAnim);
    player.setDynamicProperty("ks_pa:fall_animation", fallAnim);
    player.setDynamicProperty("ks_pa:sneak_animation", sneakAnim);
    player.setDynamicProperty("ks_pa:swim_animation", swimAnim);
    player.setDynamicProperty("ks_pa:crawl_animation", crawlAnim);
    player.setDynamicProperty("ks_pa:low_health_animation", healthAnim);
    player.setDynamicProperty("ks_pa:idle_sword_animation", idleSwordAnim);
    player.setDynamicProperty("ks_pa:attack_animations", attackAnim);
    player.setDynamicProperty("ks_pa:minecart_animation", minecartAnim);
    player.setDynamicProperty("ks_pa:stretch_animation", stretchAnim);
  });
}

function adminControls(player) {
  const allAnimations = world.getDynamicProperty("ks_pa:enableAll") || false;

  const adminMenu = new ModalFormData()
    .title("§l§5Player Animation Toggles")
    .toggle("Enable Animations for §bEveryone§r", allAnimations)
    .textField("Disable Animations For §bSpecific Players§r", "playerName1,playerName2", world.getDynamicProperty("ks_pa:disablePlayers") || "")
    .textField("Enable Animations For §bSpecific Players§r", "playerName3,playerName4", world.getDynamicProperty("ks_pa:enablePlayers") || "");

  adminMenu.show(player).then((result) => {
    if (result.canceled) return;
    let [newAllAnimations, disablePlayers, enablePlayers] = result.formValues;

    world.setDynamicProperty("ks_pa:enableAll", newAllAnimations);
    world.setDynamicProperty("ks_pa:disablePlayers", disablePlayers);
    world.setDynamicProperty("ks_pa:enablePlayers", enablePlayers);
    player.setDynamicProperty("ks_pa:changed", true);
  });
}


world.afterEvents.itemUse.subscribe(event => {
  if (event.itemStack.typeId === "ks_pa:player_menu_item") {
    settings(event.source)
  }
})
