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

let wasRedstonePresent = false;
let isCutsceneActive = false;
let wasRedstonePresentShop = false;
let isShopCutsceneActive = false;
let hasTutorialRun = false;

// Function to run commands
function runCommand(command) {
  try {
    return world.getDimension("overworld").runCommand(command);
  } catch (error) {
    console.warn("Error running command: " + command);
    console.warn(error);
  }
}

// Helper functions for cutscene actions
function cameraFade(timeIn, hold, timeOut) {
  runCommand(`camera @a fade time ${timeIn} ${hold} ${timeOut}`);
}

function cameraSet(pos, facing) {
  runCommand(`camera @a set minecraft:free pos ${pos} facing ${facing}`);
}

function cameraEase(duration, type, pos, facing) {
  runCommand(
    `camera @a set minecraft:free ease ${duration} ${type} pos ${pos} facing ${facing}`
  );
}

// Main cutscene sequence
function startCutscene() {
  const block = world
    .getDimension("overworld")
    .getBlock({ x: 65, y: -62, z: 33 });
  const isRedstonePresent = block?.typeId === "minecraft:redstone_block";

  if (isRedstonePresent && !wasRedstonePresent && !isCutsceneActive) {
    // Check if any player has the "alive" tag
    const players = world.getPlayers();
    for (const player of players) {
      if (player.hasTag("alive")) {
        runCommand("title @a actionbar §l§cGame in progress!");
        return; // Do not start cutscene
      }
    }
    isCutsceneActive = true;
    runCommand("setblock 41 -59 -56 redstone_block");
    runCommand("inputpermission set @a movement disabled");
    runCommand("inputpermission set @a camera disabled");
    runCommand("setblock 41 -59 -56 redstone_block");
    runCommand("setblock 41 -59 -56 redstone_block");
    runCommand("setblock 62 -62 33 air");
    
    system.runTimeout(() => {
      cameraFade(0.5, 3, 0.5);
      runCommand("title @a actionbar §l§eCutscene is starting!");
      runCommand("clear @a jam:extinguisher");

      // 1. First camera after 1 second
      system.runTimeout(() => {
        cameraSet("-8.64 -52.47 61.40", "42.61 -47.26 10.99");
        cameraEase(15, "linear", "40 -52.47 61.40", "42.61 -47.26 10.99");

        // 2. Fade after 5 seconds
        system.runTimeout(() => {
          cameraFade(0.5, 1, 0.5);

          // 3. Alarm2, next camera, ease after 4 seconds
          system.runTimeout(() => {
            cameraSet("19.23 -57.26 24.86", "-8.02 -53.89 50.55");
            cameraEase(15, "linear", "0 -57.26 24.86", "-8.02 -53.89 50.55");

            // 4. Fade, then after 3 seconds, new camera and ease
            system.runTimeout(() => {
              runCommand("title @a title title");

              system.runTimeout(() => {
                runCommand("title @a title subtitle");

                // 5. Dramatic overhead view after 0.5 seconds
                system.runTimeout(() => {
                  cameraFade(0.5, 1, 0.5);

                  // 6. Final clear/reset after 1 second
                  system.runTimeout(() => {
                    cameraSet("60.62 -57.53 28.05", "66.49 -56.71 22.78");
                    cameraEase(
                      15,
                      "linear",
                      "64.03 -57.53 24.94",
                      "66.49 -56.71 22.78"
                    );

                    system.runTimeout(() => {
                      cameraFade(0.5, 1, 0.5);

                      system.runTimeout(() => {
                        runCommand("tp @a 72.05 -60.78 -254.35");

                        cameraSet("66.94 -60.23 -237.11", "81.97 -57.27 -212.19");
                        cameraEase(
                          15,
                          "linear",
                          "67.14 -60.23 -223.39",
                          "81.97 -57.27 -212.19"
                        );

                        system.runTimeout(() => {
                          runCommand("title @a title jamii");

                          system.runTimeout(() => {
                            cameraFade(0.5, 1, 0.5);
                            system.runTimeout(() => {
                              runCommand("camera @a clear");
                              runCommand(
                                "inputpermission set @a movement enabled"
                              );
                              runCommand("inputpermission set @a camera enabled");

                              runCommand(
                                "tp @a 53.49 -38.00 31.52 facing 53.48 -38.00 27.63"
                              );
                              tutorialCutscene();
                              isCutsceneActive = false;
                            }, 20);
                          }, 100);
                        }, 20);
                      }, 20);
                    }, 100);
                  }, 20); // 1 second = 20 ticks
                }, 120); // 0.5 seconds = 10 ticks
              }, 70); // 3 seconds = 60 ticks
            }, 20); // 2 seconds = 40 ticks
          }, 20); // 4 seconds = 80 ticks
        }, 100); // 5 seconds = 100 ticks
      }, 60); // 1 second = 20 ticks
    }, 60); // 20-tick delay after setblock command
  }
  wasRedstonePresent = isRedstonePresent;
}

system.runInterval(startCutscene, 0); // 60 ticks = 3 seconds

function shopCutscene() {
  const block = world
    .getDimension("overworld")
    .getBlock({ x: 65, y: -62, z: 35 });
  const isRedstonePresent = block?.typeId === "minecraft:redstone_block";

  if (isRedstonePresent && !wasRedstonePresentShop && !isShopCutsceneActive) {
    // Check if any player has the "alive" tag
    const players = world.getPlayers();
    for (const player of players) {
      if (player.hasTag("alive")) {
        runCommand("title @a actionbar §l§cGame in progress!");
        return; // Do not start shop cutscene
      }
    }
    isShopCutsceneActive = true;

    // Simulate a conversation with timed messages and sound effects
    runCommand("playsound shop.dial @a ~ ~ ~ 1 1 1");
    runCommand(
      'tellraw @a {"rawtext":[{"text":"§l§eGuide: §rWelcome to the shop!"}]}'
    );
    system.runTimeout(() => {
      runCommand(
        'tellraw @a {"rawtext":[{"text":"§l§eGuide: §rHere, you can purchase all types of items you need for your fire fighting journey."}]}'
      );
      system.runTimeout(() => {
        runCommand(
          'tellraw @a {"rawtext":[{"text":"§l§eGuide: §rTake your time to browse, because each item is unique."}]}'
        );
        // Allow retriggering after the conversation
        system.runTimeout(() => {
          isShopCutsceneActive = false;
        }, 40);
      }, 75); // 2 seconds (40 ticks)
    }, 30); // 4 seconds (80 ticks)
  }
  wasRedstonePresentShop = isRedstonePresent;
}

system.runInterval(shopCutscene, 0); // 60 ticks = 3 seconds

function waitForFireSpiritDefeat(callback) {
  const overworld = world.getDimension("overworld");
  const fireEntities = overworld.getEntities({ families: ["fire"] });
  if (fireEntities.length === 0) {
    callback();
  } else {
    system.runTimeout(() => waitForFireSpiritDefeat(callback), 100);
  }
}

function tutorialCutscene() {
  if (hasTutorialRun) return; // Prevent running again
  hasTutorialRun = true;
  // Example tutorial sequence
  runCommand("tag @a add alive");
  runCommand("tag @a add tutorial");
  system.runTimeout(() => {
    runCommand("playsound tutorial.dial_1 @a ~ ~ ~ 1 1 1");
    runCommand(
      'tellraw @a {"rawtext":[{"text":"§l§bGuide: §rWelcome to the training grounds!"}]}'
    );
    system.runTimeout(() => {
      runCommand("playsound tutorial.dial_2 @a ~ ~ ~ 1 1 1");
      runCommand(
        'tellraw @a {"rawtext":[{"text":"§l§bGuide: §rHere, you will learn the basics of firefighting."}]}'
      );
      system.runTimeout(() => {
        runCommand("playsound tutorial.dial_3 @a ~ ~ ~ 1 1 1");
        runCommand(
          'tellraw @a {"rawtext":[{"text":"§l§bGuide: §rLet\'s start with the basics."}]}'
        );

        system.runTimeout(() => {
          runCommand("playsound tutorial.dial_4 @a ~ ~ ~ 1 1 1");
          runCommand(
            'tellraw @a {"rawtext":[{"text":"§l§bGuide: §rUse this extinguisher."}]}'
          );
          runCommand("give @a jam:extinguisher");
          system.runTimeout(() => {
            runCommand("playsound tutorial.dial_5 @a ~ ~ ~ 1 1 1");
            runCommand(
              'tellraw @a {"rawtext":[{"text":"§l§bGuide: §rWe can\'t extinguish the fire in the corner because the fire spirit is keeping it alive. We need to defeat the fire spirit first."}]}'
            );
            system.runTimeout(() => {
              runCommand("playsound tutorial.dial_6 @a ~ ~ ~ 1 1 1");
              runCommand(
                'tellraw @a {"rawtext":[{"text":"§l§bGuide: §rFight the fire spirit using the extinguisher."}]}'
              );
              cameraFade(0.2, 1, 0.5);
              system.runTimeout(() => {
                runCommand("summon jam:fire_small 49.49 -38.00 21.49");

                system.runTimeout(() => {
                  runCommand("playsound tutorial.dial_7 @a ~ ~ ~ 1 1 1");
                  runCommand(
                    'tellraw @a {"rawtext":[{"text":"§l§bGuide: §rNow you can extinguish the fire."}]}'
                  );
                  // Wait for fire spirit to be defeated
                  waitForFireSpiritDefeat(() => {
                    runCommand("playsound tutorial.dial_8 @a ~ ~ ~ 1 1 1");
                    runCommand(
                      'tellraw @a {"rawtext":[{"text":"§l§bGuide: §rGreat job! The fire spirit is gone."}]}'
                    );
                    system.runTimeout(() => {
                      runCommand("playsound tutorial.dial_9 @a ~ ~ ~ 1 1 1");
                      runCommand(
                        'tellraw @a {"rawtext":[{"text":"§l§bGuide: §rNow use this wand to call the water spirit to help you extinguish the fire spirit."}]}'
                      );
                      system.runTimeout(() => {
                        runCommand("give @a jam:item_wand_1 5");
                        cameraFade(0.2, 1, 0.5);
                        system.runTimeout(() => {
                          runCommand(
                            "summon jam:fire_small 49.49 -38.00 21.49"
                          );
                          system.runTimeout(() => {
                            runCommand("playsound tutorial.dial_10 @a ~ ~ ~ 1 1 1");
                            runCommand(
                              'tellraw @a {"rawtext":[{"text":"§l§bGuide: §rFight the fire spirit using the wand and summon the water spirit."}]}'
                            );
                            waitForFireSpiritDefeat(() => {
                              runCommand("playsound tutorial.dial_11 @a ~ ~ ~ 1 1 1");
                              runCommand(
                                'tellraw @a {"rawtext":[{"text":"§l§bGuide: §rGreat job! You defeated all the fire spirits. Now the fire wall will disappear."}]}'
                              );
                              system.runTimeout(() => {
                                runCommand(
                                  "particle jam:water 63.67 -37.00 22.58"
                                );
                                runCommand(
                                  "particle jam:water 65.35 -37.42 26.42"
                                );
                                runCommand(
                                  "particle jam:water 64.52 -37.42 24.28"
                                );
                                runCommand(
                                  "particle jam:water 62.70 -37.42 19.24"
                                );
                                runCommand("execute as @e[type=jam:teleporter_1] at @s run fill ~8 ~ ~8 ~-8 ~5 ~-8 air replace jam:small_fire_block");
                                runCommand("execute as @e[type=jam:teleporter_1] at @s run fill ~8 ~ ~8 ~-8 ~5 ~-8 air replace jam:two_block_fire_block");
                                runCommand("kill @e[family=water]");
                                runCommand("playsound random.fizz @a 63.67 -37.00 22.58");
                                runCommand("playsound random.fizz @a 65.35 -37.42 26.42");
                                runCommand("playsound random.fizz @a 64.52 -37.42 24.28");
                                runCommand("playsound random.fizz @a 62.70 -37.42 19.24");
                                system.runTimeout(() => {
                                  runCommand("playsound tutorial.dial_12 @a ~ ~ ~ 1 1 1");
                                  runCommand(
                                    'tellraw @a {"rawtext":[{"text":"§l§bGuide: §rYou can now head to the teleporter. In a real mission, this would take you to the next floor, but for the tutorial, we will only teleport you back to the lobby."}]}'
                                  );
                                  system.runTimeout(() => {
                                    runCommand("playsound tutorial.dial_13 @a ~ ~ ~ 1 1 1");
                                    runCommand(
                                      'tellraw @a {"rawtext":[{"text":"§l§bGuide: §rGreat! That\'s all for the tutorial. Heading back to the lobby now."}]}'
                                    );
                                    cameraFade(0.2, 1, 0.5);
                                    system.runTimeout(() => {
                                      runCommand("tag @a remove alive");
                                      runCommand("tag @a remove tutorial");
                                      runCommand("clear @a");
                                      runCommand("kill @e[family=water]");
                                      runCommand("kill @e[family=fire]");
                                      runCommand("kill @e[family=games]");
                                      runCommand(
                                        'tp @a 61.51 -58.00 37.54 facing 61.49 -58.00 31.37'
                                      );
                                      system.runTimeout(() => {
                                        runCommand("title @a title Tutorial Finished!");
                                      }, 40);
                                    }, 20);
                                  }, 200);
                                }, 80);
                              }, 100);
                            });
                          }, 60);
                        }, 20);
                      }, 100);
                    }, 100);
                  });
                }, 60);
              }, 20);
            }, 160);
          }, 40);
        }, 60); // 3 seconds
      }, 60); // 3 seconds
    }, 60); // 3 seconds
  }, 60); // 3 seconds
}

