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

// Importaciones
import "./dungeonitems.js";
import "./dungeonguide.js";
import { item_lore_event } from "./dungeonlore.js";
import { detectBlocks } from "./dungeontomb.js";
import { executeDeathCommands, moonstone, heavy_rock } from "./dungeonplayer_functions.js";
import { isLookingAtHead } from "./dungeongorgona_function.js";
import { info, detectDungeonBlocks } from "./dungeonfunctions.js";
import { cave_event } from "./dungeoncave_event.js";
import { registerBlockComponents } from "./dungeoncore.js";
import { initialize } from "./dungeonalive.js";
import { detectCloudBlocks } from "./dungeoncloudblock.js";
import fear_ui from "./fear_ui.js";
import "./dungeonsaturation.js";
import "./dungeonblocks.js";
import "./dungeonlight.js";

// Ticks por función
const INTERVAL_UI = 10;
const INTERVAL_CORE = 1;
const INTERVAL_DETECT_BLOCKS = 51;
const INTERVAL_INFO = 2;
const INTERVAL_REMOVE_VIEWING_INFO = 160;

// Contadores
let ticksUI = 0;
let ticksDetectBlocks = 0;
let ticksInfo = 0;
let ticksViewingInfo = 0;

// UI
const UIS = [fear_ui];
system.runInterval(() => {
  const players = world.getAllPlayers();
  const uiFunction = UIS[ticksUI % UIS.length];

  for (const player of players) {
    try {
      uiFunction(player);
    } catch { }
  }

  ticksUI++;
}, INTERVAL_UI);

// Evento de daño
world.afterEvents.entityHurt.subscribe(({ damageSource, hurtEntity }) => {
  heavy_rock(damageSource, hurtEntity);
});

// Lógica principal por tick
system.runInterval(() => {
  const players = world.getAllPlayers();

  for (const player of players) {
    try {
      // Siempre
      initialize(player);
      moonstone(player);
      detectCloudBlocks(player);
      executeDeathCommands(player);
      isLookingAtHead(player);

      // Cada X ticks
      if (ticksInfo % INTERVAL_INFO === 0 && player.hasTag("spectral_amulet")) {
        info(player);
        detectDungeonBlocks(player);
      }

      if (ticksDetectBlocks % INTERVAL_DETECT_BLOCKS === 0) {
        cave_event(player);
        item_lore_event(player);
        detectBlocks(player);
      }

      if (ticksViewingInfo % INTERVAL_REMOVE_VIEWING_INFO === 0) {
        system.runTimeout(() => player.removeTag("viewing_info"), 160);
      }

    } catch (e) {
      console.warn(`[ERROR] Jugador ${player.name}: ${e}`);
    }
  }

  ticksDetectBlocks++;
  ticksInfo++;
  ticksViewingInfo++;
}, INTERVAL_CORE);

// Registro de bloques
world.beforeEvents.worldInitialize.subscribe(({ blockComponentRegistry }) => {
  registerBlockComponents(blockComponentRegistry);
});
