// --- CONFIG ---
const Interval = 10; // minutes between clears
const TICKS_PER_MINUTE = 1200;
const cleaningTimeTicks = Interval * TICKS_PER_MINUTE;

const notificationsTicks = [
  5 * TICKS_PER_MINUTE,
  1 * TICKS_PER_MINUTE
];

const secondNotificationTicks = [
  5*20, 4*20, 3*20, 2*20, 1*20
];

const blacklist = ['minecraft:nether_star'];

// --- GLOBAL STATE ---
if (!global.clearLagState) {
  global.clearLagState = {
    ticks: 0,
    sentMinuteNotifications: {},
    sentSecondNotifications: {},
    lastClearItems: [],
    lastTotalCount: 0
  };
}

// --- CLEAR FUNCTION ---
let clearLagNow = (server) => {
  const state = global.clearLagState;
  const items = server.getEntities().filter(e => e.type.equals('minecraft:item'));
  const counting = Utils.newCountingMap();
  let total = 0;

  items.forEach(ent => {
    let nbt = null;
    try { nbt = ent.getNbt(); } catch(e){ nbt = null; }
    let id = nbt?.Item?.id || ent.name;

    if (!blacklist.includes(id)) {
      let count = ent.item?.count || 1;
      counting.add(id, count);
      total += count;
      try { ent.kill(); } catch(e) {}
    }
  });

  state.lastClearItems = [];
  counting.entries.forEach(pair => state.lastClearItems.push({ key: pair.key, value: pair.value }));
  state.lastTotalCount = total;

  server.tell([Text.green('[ClearLag] '), `${total}`, ' Removed items.']);
  server.tell([Text.green('[ClearLag]'), ' Clearlag will start in ', `${Interval}`, ' minutes!']);
};

// --- COMMANDS ---
ServerEvents.commandRegistry(event => {
  const { commands: Commands } = event;
  event.register(
    Commands.literal('clearlag')
      .then(Commands.literal('clear').executes(ctx => {
        clearLagNow(ctx.source.getServer());
        return 1;
      }))
      .then(Commands.literal('result').executes(ctx => {
        const state = global.clearLagState;
        const server = ctx.source.getServer();
        server.tell([Text.green('[ClearLag]'), ' Report:']);
        if (state.lastClearItems.length === 0) server.tell(['[ none ]']);
        else state.lastClearItems.forEach(r => server.tell(['[ ', r.key, ': ', r.value, ' ]']));
        return 1;
      }))
  );
});

// --- TICK-BASED SCHEDULER ---
ServerEvents.tick(event => {
  const server = event.server;
  if (!server) return;

  const state = global.clearLagState;
  state.ticks++;

  const ticksLeft = cleaningTimeTicks - state.ticks;

  // Minute notifications
notificationsTicks.forEach(nt => {
    if (ticksLeft <= nt && !state.sentMinuteNotifications[nt] && ticksLeft > 0) {
        let nextItems = server.getEntities().filter(e => e.type.equals('minecraft:item')).length;
        server.tell([Text.green('[ClearLag]'), ' Removing ', `${nextItems}`, ' items in ', `${Math.ceil(nt/TICKS_PER_MINUTE)}`, ' minutes!']);
        state.sentMinuteNotifications[nt] = true;
    }
});

// Second notifications (last minute)
if (ticksLeft <= TICKS_PER_MINUTE && ticksLeft > 0) {
    secondNotificationTicks.forEach(st => {
        if (ticksLeft <= st && !state.sentSecondNotifications[st]) {
            let nextItems = server.getEntities().filter(e => e.type.equals('minecraft:item')).length;
            server.tell([Text.green('[ClearLag]'), ' Removing ', `${nextItems}`, ' items in ', `${Math.ceil(st/20)}`, ' seconds!']);
            state.sentSecondNotifications[st] = true;
        }
    });
}


  // Automatic clearing
  if (ticksLeft <= 0) {
    clearLagNow(server);
    // reset for next cycle
    state.ticks = 0;
    state.sentMinuteNotifications = {};
    state.sentSecondNotifications = {};
  }
});
