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

const TARGET_MOB_ID = "mebesm:pj_pug_a_pillar";
const CHASE_MUSIC_ID = "pjchasetest";
const SEARCH_RADIUS = 30;
const CHECK_INTERVAL_TICKS = 20 * 5;

const DARK_PHASE_SECONDS = 3;
const LIGHT_PHASE_SECONDS = 6;

const DARK_PHASE_TICKS = 20 * DARK_PHASE_SECONDS;
const LIGHT_PHASE_TICKS = 20 * LIGHT_PHASE_SECONDS;

const CYCLE_DURATION_TICKS = DARK_PHASE_TICKS + LIGHT_PHASE_TICKS;

const EFFECT_AMPLIFIER = 255;

let minigameIntervalId = undefined;
let pugPillarEntity = undefined;

function applyVisualEffects(players, durationTicks) {
  for (const player of players) {
    if (!player.isValid()) continue;
    player.addEffect("blindness", durationTicks, { amplifier: EFFECT_AMPLIFIER, showParticles: false });
    player.addEffect("darkness", durationTicks, { amplifier: EFFECT_AMPLIFIER, showParticles: false });
    player.addEffect("slowness", durationTicks, { amplifier: EFFECT_AMPLIFIER, showParticles: false });
  }
}

function clearVisualEffects(players) {
  for (const player of players) {
    if (!player.isValid()) continue;
    player.removeEffect("blindness");
    player.removeEffect("darkness");
    player.removeEffect("slowness");
  }
}

function startMinigame(entity) {
  if (minigameIntervalId !== undefined) return;
  pugPillarEntity = entity;
  world.sendMessage(`§l§a[MINIGAME]§r Pug minigame started!`);
  runMinigameCycle();
  minigameIntervalId = system.runInterval(runMinigameCycle, CYCLE_DURATION_TICKS);
}

function stopMinigame() {
  if (minigameIntervalId === undefined) return;
  system.clearRun(minigameIntervalId);
  minigameIntervalId = undefined;
  const allPlayers = world.getAllPlayers();
  try { world.getDimension("overworld").runCommandAsync(`stopsound @a ${CHASE_MUSIC_ID}`); } catch (e) { }
  clearVisualEffects(allPlayers);
  pugPillarEntity = undefined;
  world.sendMessage(`§l§c[MINIGAME]§r Pug minigame stopped.`);
}

function runMinigameCycle() {
  if (!pugPillarEntity || !pugPillarEntity.isValid()) {
    stopMinigame();
    return;
  }

  const dimension = pugPillarEntity.dimension;

  const nearbyPlayers = dimension.getEntities({
    type: "minecraft:player",
    location: pugPillarEntity.location,
    maxDistance: SEARCH_RADIUS,
  })
    .filter(e => e instanceof Player)
    .filter(p => p.getGameMode() !== GameMode.creative && p.getGameMode() !== GameMode.spectator);

  if (nearbyPlayers.length === 0) return;

  try { dimension.runCommandAsync(`stopsound @a ${CHASE_MUSIC_ID}`); } catch (e) { }
  applyVisualEffects(nearbyPlayers, DARK_PHASE_TICKS);

  system.runTimeout(() => {
    if (!pugPillarEntity || !pugPillarEntity.isValid()) return;
    clearVisualEffects(nearbyPlayers);
    for (const player of nearbyPlayers) {
      if (!player.isValid()) continue;
      player.playSound(CHASE_MUSIC_ID, { volume: 5.0, pitch: 1.0, location: player.location });
    }
  }, DARK_PHASE_TICKS);
}

function checkPugPillarStatus() {
  if (pugPillarEntity) {
    if (!pugPillarEntity.isValid()) stopMinigame();
    return;
  }

  const dimensions = [
    world.getDimension("overworld"),
    world.getDimension("nether"),
    world.getDimension("the_end")
  ];

  for (const dim of dimensions) {
    const entities = dim.getEntities({ type: TARGET_MOB_ID, limit: 1 });
    if (entities.length > 0) {
      startMinigame(entities[0]);
      return;
    }
  }
}

world.afterEvents.worldInitialize.subscribe(() => {
  system.runInterval(checkPugPillarStatus, CHECK_INTERVAL_TICKS);
});