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

const FOG_MIN_Y = -64;
const FOG_MAX_Y = -1;

const EVENT_START = 1000;
const EVENT_END = 1500;
const EVENT_RESET = 1500;

const LOOP_TICKS = 80;

let caveFogIntervalId = null;

function getCaveEventScore() {
  try {
    const obj = world.scoreboard.getObjective("cave_fog_timer");
    const v = obj?.getScore("cave_event");
    return (v === undefined || v === null) ? 0 : v;
  } catch {
    return 0;
  }
}

function inCaveY(y) {
  return y >= FOG_MIN_Y && y <= FOG_MAX_Y;
}

function applyFogEnter(player) {
  try { player.addTag("cave_fog_active"); } catch {}

  try { player.runCommand(`fog @s push "dungeon:cave_fog" dcave_fog`); } catch {}
  try { player.runCommand(`playsound ambient.cave @s ~ ~ ~ 1 0.8`); } catch {}
  try { player.runCommand(`playsound ambient.basalt_deltas.loop @s ~ ~ ~ 0.01 0.7`); } catch {}
  try { player.runCommand(`effect @s slowness 6 1 true`); } catch {}

  if (Math.random() < 0.5) {
    const volume = (Math.random() * 0.4 + 0.2).toFixed(2);
    const pitch = (Math.random() * 0.4 + 0.6).toFixed(2);
    try { player.runCommand(`playsound ambient.cave @s ~ ~ ~ ${volume} ${pitch}`); } catch {}
  }
}

function clearFog(player) {
  try { player.removeTag("cave_fog_active"); } catch {}
  try { player.runCommand("fog @s remove dcave_fog"); } catch {}
  try { player.runCommand(`effect @s clear`); } catch {}
}

function stopFogLoop(players) {
  for (const p of players) {
    if (!p) continue;
    let hasFog = false;
    try { hasFog = p.hasTag("cave_fog_active"); } catch {}
    if (hasFog) clearFog(p);
  }
  caveFogIntervalId = null;
}

function startFogLoop() {
  if (caveFogIntervalId !== null) return;

  caveFogIntervalId = system.runInterval(() => {
    const players = world.getPlayers();
    if (players.length === 0) {
      caveFogIntervalId = null;
      return;
    }

    const score = getCaveEventScore();
    const inWindow = score >= EVENT_START && score <= EVENT_END;
    const doReset = score >= EVENT_RESET;

    let playersInCave = 0;

    for (const p of players) {
      const y = Math.floor(p.location.y);
      const inCave = inCaveY(y);

      let hasFog = false;
      try { hasFog = p.hasTag("cave_fog_active"); } catch {}

      if (doReset) {
        if (hasFog) clearFog(p);
        continue;
      }

      if (inCave) {
        playersInCave++;

        if (!hasFog && inWindow) {
          applyFogEnter(p);
        }
      } else {
        if (hasFog) {
          try { p.removeTag("cave_fog_active"); } catch {}
          try { p.runCommand("fog @s remove dcave_fog"); } catch {}
        }
      }
    }

    if (playersInCave === 0) stopFogLoop(players);
  }, LOOP_TICKS);
}

export function cave_event() {
  if (caveFogIntervalId !== null) return;

  const players = world.getPlayers();
  for (const p of players) {
    const y = Math.floor(p.location.y);
    if (inCaveY(y)) {
      startFogLoop();
      break;
    }
  }
}
