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

// Track tick, first player op, and moon state
let hasSpawnedTick = false;
let firstPlayerTagged = false;
let fullMoonActive = false;

const TICKS_PER_DAY = 24000;
let dayCounter = 0;

// Check if the np:tick entity exists
function isTickEntityAlive() {
  return [...world.getDimension("overworld").getEntities({ type: "np:tick" })].length > 0;
}

// Spawn the np:tick at first player’s location
function spawnTick() {
  const players = [...world.getPlayers()];
  if (players.length === 0) return;
  const pos = players[0].location;
  world.getDimension("overworld").spawnEntity("np:tick", pos);
  world.sendMessage("§bC§6L §7> Setting tick created.");
  hasSpawnedTick = true;
}

// Full moon detection & effect
function handleFullMoon() {
  const overworld = world.getDimension("overworld");
  const currentTime = overworld.getTimeOfDay();
  const isNight = currentTime >= 13000 && currentTime <= 23000;
  const isFullMoonDay = dayCounter % 8 === 0;

  if (isFullMoonDay && isNight && !fullMoonActive) {
    // Activate full moon
    fullMoonActive = true;
    world.sendMessage("§bC§6L §e> The Full Moon has risen...");
    
    // Tag tick entities
    for (const entity of overworld.getEntities({ families: ["tick"] })) {
      entity.addTag("flmoon");
    }
  } else if ((!isFullMoonDay || !isNight) && fullMoonActive) {
    // Reset for next full moon
    fullMoonActive = false;

    // Remove tags
    for (const entity of overworld.getEntities({ families: ["tick"] })) {
      entity.removeTag("flmoon");
    }
  }
}

// Prevent players from sleeping during full moon
function preventSleepDuringFullMoon() {
  if (!fullMoonActive) return;

  for (const player of world.getPlayers()) {
    if (player.isSleeping && player.getComponent("health")?.current > 1) {
      player.runCommandAsync("damage @s 1");
    }
  }
}

// Daily cycle tracker
let previousTime = 0;

// Main system loop
system.runInterval(() => {
  const players = [...world.getPlayers()];
  const overworld = world.getDimension("overworld");

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

  // Tick entity control
  if (!hasSpawnedTick) {
    if (!isTickEntityAlive()) {
      spawnTick();
    } else {
      hasSpawnedTick = true;
    }
  } else if (!isTickEntityAlive()) {
    spawnTick();
    world.sendMessage("§bC§6L §7> All Settings had been reset, Creating a new Setting tick");
  }

  // One-time op tag
  if (!firstPlayerTagged) {
    const player = players[0];
    if (player && !player.hasTag("op")) {
      player.addTag("op");
      firstPlayerTagged = true;
    }
  }

  // Handle moon cycle
  const currentTime = overworld.getTimeOfDay();
  if (currentTime < previousTime) {
    // New day
    dayCounter++;
  }
  previousTime = currentTime;

  // Full moon logic
  handleFullMoon();

  // Prevent sleeping
  preventSleepDuringFullMoon();

}, 20); // Every second
