const CUNICULUM_STARTER_TAG = 'cuniculum_starter_kit_v2';
const CUNICULUM_STARTER_SERVER_TAG_PREFIX = 'cuniculum_starter_kit_given_';
const CUNICULUM_STARTER_UUID_TAG_PREFIX = 'cuniculum_starter_kit_uuid_';
const CUNICULUM_FIRST_JOIN_ANNOUNCED_TAG = 'cuniculum_first_join_announced_v1';
const CUNICULUM_FIRST_JOIN_ANNOUNCED_SERVER_TAG_PREFIX = 'cuniculum_first_join_announced_';
let CUNICULUM_STARTER_DIRECTAUTH_CLASS = null;

try {
  CUNICULUM_STARTER_DIRECTAUTH_CLASS = Java.loadClass('com.marcp.directauth.DirectAuth');
} catch (ignored) {
  CUNICULUM_STARTER_DIRECTAUTH_CLASS = null;
}

const starterArmor = {
  head: `minecraft:leather_helmet[custom_name='{"text":"Capucha del Brote Cunicular","color":"aqua","italic":false}',dyed_color={rgb:3104140,show_in_tooltip:false},custom_data={cuniculum_starter:1b,cuniculum_trait:"vigia",cuniculum_trait_power:1},lore=['{"text":"Primer abrigo de quien despierta en la madriguera.","color":"gray","italic":false}'],enchantments={levels:{"minecraft:protection":1},show_in_tooltip:false}]`,
  chest: `minecraft:leather_chestplate[custom_name='{"text":"Chaleco de Pradera Joven","color":"green","italic":false}',dyed_color={rgb:4881497,show_in_tooltip:false},custom_data={cuniculum_starter:1b,cuniculum_trait:"baluarte",cuniculum_trait_power:1},lore=['{"text":"Cuero ligero para cruzar el primer prado.","color":"gray","italic":false}'],enchantments={levels:{"minecraft:protection":1},show_in_tooltip:false}]`,
  legs: `minecraft:leather_leggings[custom_name='{"text":"Pantalones de Tierra Violeta","color":"dark_purple","italic":false}',dyed_color={rgb:6966419,show_in_tooltip:false},custom_data={cuniculum_starter:1b,cuniculum_trait:"ligero",cuniculum_trait_power:1},lore=['{"text":"Cosidos para correr entre raices y senderos.","color":"gray","italic":false}'],enchantments={levels:{"minecraft:protection":1},show_in_tooltip:false}]`,
  feet: `minecraft:leather_boots[custom_name='{"text":"Botas del Primer Salto","color":"gold","italic":false}',dyed_color={rgb:13208122,show_in_tooltip:false},custom_data={cuniculum_starter:1b,cuniculum_trait:"salto",cuniculum_trait_power:1},lore=['{"text":"Un pequeno favor para sobrevivir al primer tropiezo.","color":"gray","italic":false}'],enchantments={levels:{"minecraft:feather_falling":1},show_in_tooltip:false}]`
};

const starterItems = [
  [`minecraft:wooden_sword[custom_name='{"text":"Rama del Vigia Novato","color":"gold","italic":false}',custom_data={cuniculum_starter:1b,cuniculum_trait:"devastador",cuniculum_trait_power:1},lore=['{"text":"Arma sencilla de recluta: sirve para aprender, no para presumir.","color":"gray","italic":false}'],enchantments={levels:{"minecraft:unbreaking":1},show_in_tooltip:false}]`, 1],
  [`minecraft:wooden_pickaxe[custom_name='{"text":"Pico de Raiz Tierna","color":"yellow","italic":false}',custom_data={cuniculum_starter:1b,cuniculum_trait:"tunelero",cuniculum_trait_power:1},lore=['{"text":"Para abrir el primer tunel sin saltarse la progresion.","color":"gray","italic":false}'],enchantments={levels:{"minecraft:unbreaking":1},show_in_tooltip:false}]`, 1],
  [`minecraft:wooden_axe[custom_name='{"text":"Hacha de Rama Clara","color":"green","italic":false}',custom_data={cuniculum_starter:1b,cuniculum_trait:"lenador",cuniculum_trait_power:1},lore=['{"text":"Herramienta humilde para levantar el primer refugio.","color":"gray","italic":false}'],enchantments={levels:{"minecraft:unbreaking":1},show_in_tooltip:false}]`, 1],
  [`minecraft:wooden_shovel[custom_name='{"text":"Pala del Primer Tunel","color":"aqua","italic":false}',custom_data={cuniculum_starter:1b,cuniculum_trait:"excavador",cuniculum_trait_power:1},lore=['{"text":"La madriguera siempre empieza con tierra removida.","color":"gray","italic":false}'],enchantments={levels:{"minecraft:unbreaking":1},show_in_tooltip:false}]`, 1],
  [`minecraft:shield[custom_name='{"text":"Escudo del Prado Bajo","color":"dark_aqua","italic":false}',custom_data={cuniculum_starter:1b,cuniculum_trait:"baluarte",cuniculum_trait_power:1},lore=['{"text":"Un pequeno frente de madera para sobrevivir a la primera noche.","color":"gray","italic":false}'],enchantments={levels:{"minecraft:unbreaking":1},show_in_tooltip:false}]`, 1],
  [`minecraft:bread[custom_name='{"text":"Pan de Zanahoria de Viaje","color":"yellow","italic":false}',lore=['{"text":"Racion sencilla de bienvenida de la madriguera.","color":"gray","italic":false}']]`, 10],
  [`minecraft:carrot[custom_name='{"text":"Zanahorias del Sendero","color":"gold","italic":false}',lore=['{"text":"No es lujo; es tradicion cunicular.","color":"gray","italic":false}']]`, 8],
  [`minecraft:torch[custom_name='{"text":"Luciernagas de Bolsillo","color":"gold","italic":false}',lore=['{"text":"Para que el primer tunel no te coma entero.","color":"gray","italic":false}']]`, 20],
  [`ftbquests:book[custom_name='{"text":"Bitacora del Conejo Errante","color":"light_purple","italic":false}',lore=['{"text":"Tu guia inicial para avanzar en CUNICULUM.","color":"gray","italic":false}']]`, 1],
  [`lightmanscurrency:wallet_leather[custom_name='{"text":"Monedero de la Madriguera","color":"green","italic":false}',lore=['{"text":"Guarda tus primeras monedas del valle.","color":"gray","italic":false}']]`, 1],
  [`lightmanscurrency:coin_copper`, 16]
];

function applyCuniculumWorldRules(server) {
  [
    'difficulty hard',
    'gamerule keepInventory false',
    'gamerule announceAdvancements false',
    'gamerule mobGriefing false',
    'gamerule doFireTick false',
    'gamerule doInsomnia false',
    'kill @e[type=minecraft:phantom]',
    'gamerule doPatrolSpawning true',
    'gamerule doTraderSpawning true',
    'gamerule logAdminCommands true',
    'gamerule commandBlockOutput false',
    'gamerule sendCommandFeedback false',
    'gamerule playersSleepingPercentage 50'
  ].forEach(command => server.runCommandSilent(command));
}

ServerEvents.loaded(event => {
  applyCuniculumWorldRules(event.server);
});

function cuniculumStarterSafeKey(value) {
  return String(value || '').toLowerCase().replace(/[^a-z0-9_-]/g, '_');
}

function cuniculumStarterUuid(player) {
  const values = [];

  try {
    values.push(player.uuid);
  } catch (ignored) {
  }

  try {
    values.push(player.getUUID());
  } catch (ignored) {
  }

  try {
    values.push(player.getUuid());
  } catch (ignored) {
  }

  var candidateUuid = '';
  for (let i = 0; i < values.length; i++) {
    candidateUuid = String(values[i] || '').trim();
    if (candidateUuid && candidateUuid !== 'undefined' && candidateUuid !== 'null') {
      return candidateUuid;
    }
  }

  return '';
}

function cuniculumStarterServerKeys(player, name) {
  const keys = [CUNICULUM_STARTER_SERVER_TAG_PREFIX + cuniculumStarterSafeKey(name)];
  const uuid = cuniculumStarterUuid(player);
  if (uuid) {
    keys.push(CUNICULUM_STARTER_UUID_TAG_PREFIX + cuniculumStarterSafeKey(uuid));
  }
  return keys;
}

function cuniculumStarterHasMarker(player, server, keys) {
  if (player.persistentData[CUNICULUM_STARTER_TAG]) {
    return true;
  }

  for (let i = 0; i < keys.length; i++) {
    if (server.persistentData[keys[i]]) {
      return true;
    }
  }

  return false;
}

function cuniculumStarterMarkGiven(player, server, keys) {
  player.persistentData[CUNICULUM_STARTER_TAG] = true;
  for (let i = 0; i < keys.length; i++) {
    server.persistentData[keys[i]] = true;
  }
}

function cuniculumStarterIsAuthenticated(player) {
  if (!player || !CUNICULUM_STARTER_DIRECTAUTH_CLASS) {
    return true;
  }

  let manager = null;
  try {
    manager = CUNICULUM_STARTER_DIRECTAUTH_CLASS.getLoginManager();
  } catch (ignored) {
    return false;
  }

  if (!manager) {
    return false;
  }

  const candidates = [player];
  try { candidates.push(player.minecraftEntity); } catch (ignored) { }
  try { candidates.push(player.entity); } catch (ignored) { }
  try { candidates.push(player.getEntity()); } catch (ignored) { }

  for (let i = 0; i < candidates.length; i++) {
    if (!candidates[i]) {
      continue;
    }
    try {
      return !!manager.isAuthenticated(candidates[i]);
    } catch (ignored) { }
  }

  return false;
}

function cuniculumAnnounceFirstJoin(player, server, keys) {
  if (player.persistentData[CUNICULUM_FIRST_JOIN_ANNOUNCED_TAG]) {
    return;
  }

  for (let i = 0; i < keys.length; i++) {
    const announceKey = CUNICULUM_FIRST_JOIN_ANNOUNCED_SERVER_TAG_PREFIX + cuniculumStarterSafeKey(keys[i]);
    if (server.persistentData[announceKey]) {
      player.persistentData[CUNICULUM_FIRST_JOIN_ANNOUNCED_TAG] = true;
      return;
    }
  }

  player.persistentData[CUNICULUM_FIRST_JOIN_ANNOUNCED_TAG] = true;
  for (let i = 0; i < keys.length; i++) {
    const announceKey = CUNICULUM_FIRST_JOIN_ANNOUNCED_SERVER_TAG_PREFIX + cuniculumStarterSafeKey(keys[i]);
    server.persistentData[announceKey] = true;
  }

  // DirectAuth debe ser el primer texto visible al entrar; no se anuncia antes del login.
}

function cuniculumStarterTryGive(player, server) {
  if (!player || !server) {
    return false;
  }

  const name = player.username;
  if (!cuniculumStarterIsAuthenticated(player)) {
    return false;
  }

  const serverKeys = cuniculumStarterServerKeys(player, name);
  if (cuniculumStarterHasMarker(player, server, serverKeys)) {
    cuniculumStarterMarkGiven(player, server, serverKeys);
    return true;
  }

  cuniculumStarterMarkGiven(player, server, serverKeys);
  cuniculumAnnounceFirstJoin(player, server, serverKeys);

  server.runCommandSilent(`item replace entity ${name} armor.head with ${starterArmor.head} 1`);
  server.runCommandSilent(`item replace entity ${name} armor.chest with ${starterArmor.chest} 1`);
  server.runCommandSilent(`item replace entity ${name} armor.legs with ${starterArmor.legs} 1`);
  server.runCommandSilent(`item replace entity ${name} armor.feet with ${starterArmor.feet} 1`);

  starterItems.forEach(entry => {
    server.runCommandSilent(`give ${name} ${entry[0]} ${entry[1]}`);
  });

  server.runCommandSilent(`effect give ${name} minecraft:resistance 90 0 true`);
  return true;
}

function cuniculumStarterScheduleChecks(server, player) {
  [20, 80, 160, 300, 600, 1200].forEach(delay => {
    server.scheduleInTicks(delay, function () {
      cuniculumStarterTryGive(player, server);
    });
  });
}

PlayerEvents.loggedIn(event => {
  const player = event.player;
  const server = event.server;

  applyCuniculumWorldRules(server);
  cuniculumStarterTryGive(player, server);
  cuniculumStarterScheduleChecks(server, player);
});

PlayerEvents.tick(event => {
  const player = event.player;
  const server = event.server;
  if (!player || !server || player.age % 20 !== 0) {
    return;
  }

  if (player.persistentData[CUNICULUM_STARTER_TAG]) {
    return;
  }

  cuniculumStarterTryGive(player, server);
});
