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

const pts_lvl = 5; 
const obj_pts = "attribute_point"; 
const obj_tkr = "level_tracker"; 

let duration_ecl = 1200; 

function finalizar_ecl(player, sacrifícios, p_marker, resultado, p_loc, area_nome) {
    try {
        const dim = world.getDimension("overworld");

        if (player && player.isValid()) {
            player.removeTag("eclipse_em_curso");
  player.removeTag("i_sacrifice");
            player.removeTag("i_dont_sacrifice");
       player.removeTag("start_eclipse");

            if (p_marker && p_marker.isValid()) {
           player.teleport(p_marker.location);
            } else {
        player.teleport(p_loc);
            }

            if (resultado === "recusou") {
                player.addTag("marca_sacrificio");
          player.sendMessage("§cYou denied the offer...");
            } else if (resultado === "sucesso") {
        player.runCommandAsync("title @s title §4Sacrifice Accepted");
        player.addTag("apostle");
                player.addTag("femto");
            }
      player.sendMessage("§8The Eclipse has ended.");
        }

        sacrifícios.forEach(s => {
            if (s.ent && s.ent.isValid()) {
                s.ent.removeTag("sacrifice");
      s.ent.removeEffect("levitation"); 
                
                if (resultado === "sucesso") {
                    s.ent.addTag("marca_sacrificio");
           s.ent.applyDamage(9999);
                } else if (s.marker && s.marker.isValid()) {
                    s.ent.teleport(s.marker.location);
                }
            }
     if (s.marker && s.marker.isValid()) s.marker.remove();
        });

        if (p_marker && p_marker.isValid()) p_marker.remove();

        dim.runCommandAsync(`tickingarea remove ${area_nome}_r`);
     dim.runCommandAsync(`tickingarea remove ${area_nome}_e`);
  dim.runCommandAsync("kill @e[type=nb:void]");
     dim.runCommandAsync("kill @e[type=nb:slan]");
        dim.runCommandAsync("kill @e[type=nb:caveira]");
        
    } catch (e) {
        console.warn("Erro ao finalizar eclipse: " + e);
    }
}

function iniciar_ritual_eclipse(player) {
    if (!player || !player.isValid()) return;

    const dim = player.dimension;
    const p_loc = { x: player.location.x, y: player.location.y, z: player.location.z };
    const e_loc = { x: 0, y: 200, z: 0 }; 
    const area_nome = "ecl" + Math.floor(Math.random() * 999);

    try {
        dim.runCommandAsync(`tickingarea add circle ${p_loc.x} ${p_loc.z} 2 ${area_nome}_r`);
     dim.runCommandAsync(`tickingarea add circle ${e_loc.x} ${e_loc.z} 2 ${area_nome}_e`);

        const p_marker = dim.spawnEntity("minecraft:armor_stand", p_loc);
        p_marker.nameTag = `RET_${player.name}`;
  p_marker.addEffect("invisibility", 20000, { showParticles: false });

        const sacrifícios = [];
        const detectados = dim.getEntities({ 
            location: p_loc, 
            maxDistance: 25, 
            excludeTypes: ["minecraft:player", "minecraft:armor_stand", "minecraft:item", "nb:void", "nb:slan"] 
        });
        
        for (const m of detectados) {
            if (m.isValid()) {
                m.addTag("sacrifice"); 
                m.addEffect("resistance", 200, { amplifier: 255, showParticles: false });
                
                const m_marker = dim.spawnEntity("minecraft:armor_stand", m.location);
        m_marker.addEffect("invisibility", 20000, { showParticles: false });
                
                sacrifícios.push({ ent: m, marker: m_marker });
            }
        }

        player.runCommandAsync("camera @s fade time 0.5 30 0.5 color 0 0 0");
        
        system.runTimeout(() => {
            if (!player.isValid()) return;
            
            dim.runCommandAsync(`structure load eclipse 0 199 0 180_degrees none`);
            
            player.teleport(e_loc);
            
            sacrifícios.forEach(s => {
                if (s.ent.isValid()) {
              s.ent.teleport({ x: e_loc.x, y: e_loc.y + 5, z: e_loc.z });
        s.ent.addEffect("levitation", 200, { amplifier: 255, showParticles: false });
                    s.ent.addEffect("resistance", 200, { amplifier: 255, showParticles: false });
                }
            });

            let ticks_wait = 0;
            
            const monitor = system.runInterval(() => {
                ticks_wait++;
                
                const d1 = dim.getEntities({ name: "eclipse_tp_inicial", location: e_loc, maxDistance: 60 })[0];
       const d2 = dim.getEntities({ name: "beherit_user_tp", location: e_loc, maxDistance: 60 })[0];

                if ((d1 && d2) || ticks_wait > 100) {
                    system.clearRun(monitor);
                    
                    const spawn_mobs = d1 ? { x: d1.location.x, y: d1.location.y + 1, z: d1.location.z } : { x: e_loc.x, y: e_loc.y + 1, z: e_loc.z };
                    
                    sacrifícios.forEach(s => { 
                        if (s.ent.isValid()) {
                    s.ent.teleport(spawn_mobs);
              s.ent.removeEffect("levitation");
                            s.ent.removeEffect("resistance");                            
                        }
                    });
                    
                    if (d2 && player.isValid()) player.teleport(d2.location);

                    let ritual_ticks = 0;
                    let spawned_apostolos = false;
                    
                    const ritual_loop = system.runInterval(() => {
                        if (!player.isValid() || player.hasTag("i_dont_sacrifice")) {
                            system.clearRun(ritual_loop);
                      finalizar_ecl(player, sacrifícios, p_marker, "recusou", p_loc, area_nome);
                            return;
                        }

                        if (player.hasTag("i_sacrifice")) {
                            if (!spawned_apostolos) {
                                const lista_de_summons = ["summon_apostolo", "summon_apostolos2", "summon_apostolos3"];
                                
                                lista_de_summons.forEach(tag_nome => {
                                    const locs = dim.getEntities({ location: e_loc, maxDistance: 100, name: tag_nome });
                                    locs.forEach(l => {
                                        const view = l.getViewDirection();
                                        const pos_final = {
                                            x: l.location.x + (view.x * 2),
                                            y: l.location.y,
                                            z: l.location.z + (view.z * 2)
                                        };
                                        dim.spawnEntity("nb:caveira", pos_final);
                                    });
                                });
                                spawned_apostolos = true;
                            }

                            ritual_ticks++;
                            
                            const vivos = sacrifícios.filter(s => {
                                if (!s.ent.isValid()) return false;
                                const hp = s.ent.getComponent("health");
                                return hp && hp.currentValue > 0;
                            });
                
                            if (ritual_ticks >= duration_ecl || (sacrifícios.length > 0 && vivos.length === 0)) {
                                system.clearRun(ritual_loop);
                          finalizar_ecl(player, sacrifícios, p_marker, "sucesso", p_loc, area_nome);
                                return;
                            }

                            if (ritual_ticks % 20 === 0) {
                                let seg = Math.ceil((duration_ecl - ritual_ticks) / 20);
                          player.onScreenDisplay.setActionBar(`§cTimer: ${seg}s | Sacrifices: ${vivos.length}`);
                            }
                        } else {
                            if (system.currentTick % 40 === 0) {
                                player.onScreenDisplay.setActionBar("§fChoose your destiny...");
                            }
                        }
                    }, 1);
                }
            }, 5);
        }, 20);

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

system.runInterval(() => {
    try {
        const sbPoints = world.scoreboard.getObjective(obj_pts) || world.scoreboard.addObjective(obj_pts, "§6Attribute Points");
        const sbTracker = world.scoreboard.getObjective(obj_tkr) || world.scoreboard.addObjective(obj_tkr, "Level Tracker");

        for (const player of world.getPlayers()) {
            if (!player.isValid()) continue;

            const cur_lvl = player.level;
            let last_lvl = 0;
            if (sbTracker.hasParticipant(player)) last_lvl = sbTracker.getScore(player);
            
            if (cur_lvl >= last_lvl + pts_lvl) {
                const diff = Math.floor((cur_lvl - last_lvl) / pts_lvl);
                sbPoints.addScore(player, diff);
          sbTracker.setScore(player, last_lvl + (diff * pts_lvl));
                player.sendMessage(`§eLevel up! §a+${diff} Points.`);
            }

            if (player.hasTag("start_eclipse") && !player.hasTag("eclipse_em_curso")) {
                player.removeTag("start_eclipse");
           player.addTag("eclipse_em_curso");
                iniciar_ritual_eclipse(player);
            }
        }
    } catch (e) {}
}, 20);