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

function getInsomnioLevel(score) {
  if (score >= 450000) return 20;
  if (score >= 95991) return 19;
  if (score >= 90000) return 18;
  if (score >= 85000) return 17;
  if (score >= 80000) return 16;
  if (score >= 75000) return 15;
  if (score >= 70000) return 14;
  if (score >= 65000) return 13;
  if (score >= 60000) return 12;
  if (score >= 55000) return 11;
  if (score >= 50000) return 10;
  if (score >= 45000) return 9;
  if (score >= 40000) return 8;
  if (score >= 35000) return 7;
  if (score >= 30000) return 6;
  if (score >= 25000) return 5;
  if (score >= 20000) return 4;
  if (score >= 15000) return 3;
  if (score >= 10000) return 2;
  if (score >= 5000) return 1;
  return 0;
}

function getScore(objective, player) {
  try {
    const s = objective.getScore(player);
    return typeof s === "number" ? s : 0;
  } catch {
    return 0;
  }
}

const lastLevel = new Map();

// Intervalos (ticks)
const UPDATE_LEVEL_EVERY = 5;   // calcula nivel frecuentemente
const RESEND_TITLE_EVERY = 50;  // reafirma el título cada 0.75s (15 ticks)

// Estado para reafirmar
let resendCounter = 0;

function pushFearTitle(player, lvl) {
  // IMPORTANTE: empieza con '!' para que el title vanilla se oculte con el filtro
  player.onScreenDisplay.setTitle(`!fear.${lvl}.${lvl}`);
}

system.runInterval(() => {
  const obj = world.scoreboard.getObjective("insomnio");
  if (!obj) return;

  //Recalcular y enviar al cambiar
  for (const p of world.getAllPlayers()) {
    const lvl = getInsomnioLevel(getScore(obj, p));
    const prev = lastLevel.get(p.id);

    if (prev !== lvl) {
      lastLevel.set(p.id, lvl);
      pushFearTitle(p, lvl);
    }
  }

  // Reafirmar por si otro addon pisó el title
  resendCounter += UPDATE_LEVEL_EVERY;
  if (resendCounter >= RESEND_TITLE_EVERY) {
    resendCounter = 0;
    for (const p of world.getAllPlayers()) {
      const lvl = lastLevel.get(p.id);
      if (typeof lvl === "number") {
        pushFearTitle(p, lvl);
      }
    }
  }
}, UPDATE_LEVEL_EVERY);
