import { world, ItemStack } from '@minecraft/server';
import { holiDates, getDateRangeInfo } from './holidays.js';
import { getHolidaySpawnChance, getLegendarySpawnChance } from './spawnConfigUI.js';

world.afterEvents.entityDie.subscribe((event) => {
  const deadEntity = event.deadEntity;
  //
  const damageSource = event.damageSource;
  const cause = damageSource.cause;
  const damagingEntity = damageSource.damagingEntity;
  const damagingProjectile = damageSource.damagingProjectile;
  
  const family = deadEntity.getComponent('type_family');

  if (
    deadEntity.typeId === 'minecraft:player' ||
    deadEntity.typeId === 'minecraft:item' ||
    family.hasTypeFamily('inanimate')
  ) {
    return;
  }

  const deadEntityDimension = deadEntity.dimension;
  const deadEntityLocation = deadEntity.location;
  const deadEntityTypeId = deadEntity.typeId;

  const now = new Date();
  const easter = getDateRangeInfo(now, holiDates.easter, { weeks: 1 });
  const summer = getDateRangeInfo(now, holiDates.summer, { weeks: 1 });
  const halloween = getDateRangeInfo(now, holiDates.halloween, { weeks: 1 });
  const festive = getDateRangeInfo(now, holiDates.festive, { weeks: 1 });
  const today = getDateRangeInfo(now, now, { days: 1 });

  if (Math.random() <= getHolidaySpawnChance()) {
    if (today.isInRange) {
      deadEntityDimension.spawnItem(new ItemStack('just:cosmetic_bag', 1), deadEntityLocation);
    } else if (easter.isInRange) {
      deadEntityDimension.spawnItem(new ItemStack('just:hatbag_easter', 1), deadEntityLocation);
    } else if (summer.isInRange) {
      deadEntityDimension.spawnItem(new ItemStack('just:hatbag_summer', 1), deadEntityLocation);
    } else if (halloween.isInRange) {
      deadEntityDimension.spawnItem(new ItemStack('just:hatbag_halloween', 1), deadEntityLocation);
    } else if (festive.isInRange) {
      deadEntityDimension.spawnItem(new ItemStack('just:hatbag_festive', 1), deadEntityLocation);
    }
  }

  const health = deadEntity.getComponent('health')?.effectiveMax;
  if (Math.random() <= getLegendarySpawnChance()) {
    if (health >= 80 && health <= 10000) {
      deadEntityDimension.spawnItem(new ItemStack('just:hatscraps_legendary', 1), deadEntityLocation);
    }
  }
});