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

import "./weather.js"
import "./music.js"
import "./test1.js"
import "./test2.js"
import "./dialogue.js"
import "./meter.js"

try {
  (async () => {
    try {
      await import("./winter.js");
    } catch (e) {
      console.warn("winter.js not found");
    }

    const messages = [
      "scrumptious",
      "succulent",
      "piquant"
    ]

    const random_events = [
      {
        chance: 0.08,
        action: (player) => {
          player.playSound("whisper", { volume: 0.2, pitch: 1 })
          player.sendMessage(" Come closer..")
          system.runTimeout(() => {
            player.sendMessage(" You are destined")
          }, 30)
        }
      },
      {
        chance: 0.09,
        action: (player) => {
          const r = messages[Math.floor(Math.random() * messages.length)]
          player.playSound("whisper", { volume: 0.2, pitch: 1 })
          player.sendMessage(" The smell of blood...")
          system.runTimeout(() => {
            player.sendMessage(" The smell of meat...")
          }, 30)
          system.runTimeout(() => {
            player.sendMessage(`How ${r}, isn't it?`)
          }, 35)
        }
      }
    ]

    const playerData = new Map()
    const curse_start = 1000

    function initPlayer(p) {
      if (!playerData.has(p.id)) {
        playerData.set(p.id, {
          progress: 0,
          lastWhisper: 0
        })
      }
    }

    world.afterEvents.playerSpawn.subscribe(ev => {
      const p = ev.player
      initPlayer(p)
      if (!p.hasTag("despawn_wen")) p.addTag("despawn_wen")
    })

    system.runInterval(() => {
      for (const p of world.getAllPlayers()) {
        initPlayer(p)
        const d = playerData.get(p.id)
        d.progress += 1
      }
    }, 70)

    world.afterEvents.entityDie.subscribe(ev => {
      const killer = ev.damageSource?.damagingEntity
      if (killer && killer.typeId === "minecraft:player") return
      for (const p of world.getAllPlayers()) {
        initPlayer(p)
        const d = playerData.get(p.id)
        d.progress += 20
      }
    })

    system.runInterval(() => {
      for (const p of world.getAllPlayers()) {
        if (p.hasTag("curse_done")) continue
        initPlayer(p)
        const d = playerData.get(p.id)

        if (d.progress >= curse_start) {
          p.addTag("curse_done")
          p.addTag("no_cooked_meat")
          p.addTag("cursed")
          p.addTag("grab")
          p.addTag("message")
          p.runCommand('summon kick:wendigo_curse ~ ~ ~1')
          p.removeTag("despawn_wen")

          system.runTimeout(() => {
            p.removeTag("grab")
          }, 40)

          p.runCommand('playsound wendigo_roar1 @s')

          system.runTimeout(() => {
            p.runCommand('event entity @e[type=kick:wendigo_curse] kick:despawn')
          }, 27.586)

          system.runTimeout(() => {
            p.removeTag("grab")
            p.runCommand('effect @s hunger infinite 10 true')
            p.runCommand('effect @s nausea 10 20 true')
          }, 20)
        }
      }
    }, 50)

    system.runInterval(() => {
      const now = Date.now()
      for (const p of world.getAllPlayers()) {
        if (!p.hasTag("message")) continue
        initPlayer(p)
        const d = playerData.get(p.id)
        if (now - d.lastWhisper < 45000) continue
        d.lastWhisper = now

        for (const r of random_events) {
          if (Math.random() < r.chance) {
            r.action(p)
          }
        }
      }
    }, 20)

    system.runInterval(() => {
      for (const p of world.getAllPlayers()) {
        if (p.hasTag("despawn_wen")) {
          for (const wen of p.dimension.getEntities({ type: "kick:wendigo_player" })) {
            wen.remove()
          }
        }
      }
    }, 10)
    system.runInterval(() => {
      for (const player of world.getAllPlayers()) {
        if (player.hasTag("no_cooked_meat")) {
          player.runCommand('effect @s hunger infinite 10 true')
        }
      }
    }, 20)
    world.afterEvents.entityHitEntity.subscribe(ev => {
      const a = ev.damagingEntity
      const b = ev.hitEntity
      const eq = a.getComponent("minecraft:equippable")
      const held = eq?.getEquipment(EquipmentSlot.Mainhand)
      if (held && held.typeId === "kick:silver_sword" && b.typeId === "kick:wendigo_player_real") {
        try { b.applyDamage(7) } catch { }
      }
    })

    world.beforeEvents.itemUse.subscribe(ev => {
      const item = ev.itemStack
      const p = ev.source

      const eat = [
        "minecraft:beef",
        "minecraft:mutton",
        "minecraft:chicken",
        "minecraft:cod",
        "minecraft:salmon",
        "minecraft:porkchop",
        "minecraft:pufferfish",
        "minecraft:tropical_fish",
        "kick:human_flesh"
      ]

      const cant_eat = [
        "minecraft:cooked_beef",
        "minecraft:cooked_mutton",
        "minecraft:cooked_chicken",
        "minecraft:cooked_cod",
        "minecraft:cooked_salmon",
        "minecraft:cooked_porkchop",
        "minecraft:cooked_rabbit",
        "minecraft:cookie",
        "minecraft:bread",
        "minecraft:golden_apple",
        "minecraft:enchanted_golden_apple",
        "minecraft:golden_carrot",
        "minecraft:melon_slice",
        "minecraft:beetroot",
        "minecraft:beetroot_soup",
        "minecraft:apple",
        "minecraft:carrot",
        "minecraft:potato",
        "minecraft:baked_potato",
        "minecraft:dried_kelp",
        "minecraft:mushroom_stew",
        "minecraft:pumpkin_pie",
        "minecraft:sweet_berries",
        "minecraft:glow_berries",
        "minecraft:chorus_fruit",
        "minecraft:honey_bottle",
        "minecraft:cake"
      ]

      if (p.hasTag("no_cooked_meat") && cant_eat.includes(item.typeId)) {
        ev.cancel = true
        system.run(() => {
          p.onScreenDisplay.setActionBar("You don't feel like eating this..")
        })
      }

      if (p.hasTag("no_cooked_meat") && eat.includes(item.typeId)) {
        system.run(() => {
          if (Math.random() < 0.04) {
            p.runCommand('effect @s nausea 10 20 true')
          }
        })
      }
    })

    world.beforeEvents.itemUseOn.subscribe(ev => {
      const block = ev.block
      const p = ev.source
      if (p.hasTag("no_cooked_meat") && block && block.typeId === "minecraft:cake") {
        ev.cancel = true
        system.run(() => {
          p.onScreenDisplay.setActionBar("You don't feel like eating this..")
        })
      }
    })

  })()
} catch (e) {
  console.warn(e)
}