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

const sleepState = new Map();
let lastTime = world.getTimeOfDay();

system.runTimeout(() => {
  world.sendMessage("§aYou're next mission....");
}, 20);

// 玩家第一次進入世界時顯示歡迎訊息
world.afterEvents.playerSpawn.subscribe(event => {
  if (event.initialSpawn) {
    const player = event.player;
    player.sendMessage("You're next mission....");
  }
});

/* ===================== 新增：互動實體播放音效 ===================== */
world.afterEvents.playerInteractWithEntity.subscribe(ev => {
  const player = ev.player;
  const entity = ev.target;

  if (!entity) return;

  if (entity.typeId === "rider:capsem_dropper") {
    // 播放音效（播給互動的玩家）
    player.playSound("capsem_dropper");
  }
});
/* ================================================================ */

system.runInterval(() => {

  const currentTime = world.getTimeOfDay();

  // 判斷是否「剛跳過夜晚」
  const nightSkipped =
    (lastTime > 13000 && currentTime < 1000);

  lastTime = currentTime;

  for (const player of world.getAllPlayers()) {
    try {
      const gamemode = player.getGameMode();
      const variantComp = player.getComponent("minecraft:variant");
      const variant = variantComp?.value ?? 0;
      const isFlying = player.isFlying ?? false;

      // ====== 睡醒且成功跳過夜晚判定 ======
      const wasSleeping = sleepState.get(player.id) ?? false;
      const isSleeping = player.isSleeping ?? false;

      if (nightSkipped && wasSleeping && !isSleeping) {
        player.runCommandAsync("replaceitem entity @s[tag=!story_start] slot.armor.chest 1 rider:zeztz_driver");
        player.runCommandAsync("event entity @s[tag=!story_start] rider:story_start");
        player.runCommandAsync("tag @s add story_start");
      }

      sleepState.set(player.id, isSleeping);
      // ====================================

      // 創造模式永遠允許飛行
      if (gamemode === GameMode.creative) {
        player.runCommandAsync("ability @s mayfly true");
        player.runCommandAsync("gamerule sendcommandfeedback false");
        continue;
      }

      // 飛行條件
      if (variant === 4) {
        player.runCommandAsync("ability @s mayfly true");
        if (isFlying) {
          player.runCommandAsync("event entity @s nido:flying");
        } else {
          player.runCommandAsync("event entity @s nido:flying.off");
        }
      } 
      // 其他玩家關閉飛行
      else {
        player.runCommandAsync("ability @s mayfly false");
        player.runCommandAsync("event entity @s nido:flying.off");
      }

    } catch (e) {
      player.runCommandAsync("ability @s mayfly false");
      player.runCommandAsync("event entity @s nido:flying.off");
    }
  }
}, 20);
