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





const TORCH_ID = "xaierg:linterna";
const TORCH_OFF_ID = "xaierg:linterna_apagada";
const LIGHT_REMOVAL_DELAY = 20; // ticks (1 segundo)
const BATTERY_ID = "xaierg:bateria_linterna";
const TORCH_TIMER_SECONDS = 600; // 5 minutos

const playerLights = new Map();
const torchTimers = new Map(); // playerId -> { secondsLeft, active }

function getFlooredPosition(location) {
    return {
        x: Math.floor(location.x),
        y: Math.floor(location.y),
        z: Math.floor(location.z)
    };
}

function positionsEqual(pos1, pos2) {
    return pos1.x === pos2.x && pos1.y === pos2.y && pos1.z === pos2.z;
}

function canPlaceLightBlock(dimension, position) {
    try {
        const block = dimension.getBlock(position);
        return block && (block.typeId === "minecraft:air" || block.typeId === "minecraft:light_block");
    } catch {
        return false;
    }
}

function placeLightBlock(dimension, position) {
    if (!canPlaceLightBlock(dimension, position)) return false;
    const { x, y, z } = position;
    try {
        dimension.runCommand(`fill ${x} ${y} ${z} ${x} ${y} ${z} light_block_15 replace air`);
        return true;
    } catch { return false; }
}

function removeLightBlock(dimension, position) {
    const { x, y, z } = position;
    try {
        dimension.runCommand(`fill ${x} ${y} ${z} ${x} ${y} ${z} air replace light_block_15`);
        return true;
    } catch { return false; }
}

function removePlayerLightImmediate(playerId) {
    const lightData = playerLights.get(playerId);
    if (lightData) {
        const dimension = world.getDimension(lightData.dimensionId);
        if (dimension) {
            removeLightBlock(dimension, lightData.position);
            removeLightBlock(dimension, { x: lightData.position.x, y: lightData.position.y + 1, z: lightData.position.z });
        }
        playerLights.delete(playerId);
    }
}

function isHoldingTorch(player) {
    try {
        const eq = player.getComponent("minecraft:equippable");
        if (!eq) return false;
        const main = eq.getEquipment("Mainhand");
        const off = eq.getEquipment("Offhand");
        return (main && main.typeId === TORCH_ID) || (off && off.typeId === TORCH_ID);
    } catch { return false; }
}

function isHoldingTorchAny(player) {
    try {
        const eq = player.getComponent("minecraft:equippable");
        if (!eq) return false;
        const main = eq.getEquipment("Mainhand");
        const off = eq.getEquipment("Offhand");
        return (main && main.typeId === TORCH_ID) || (off && off.typeId === TORCH_ID);
    } catch { return false; }
}

function updateDynamicTorchLight() {
    for (const player of world.getAllPlayers()) {
        const playerId = player.id;
        const currentPos = getFlooredPosition(player.location);
        const abovePos = { x: currentPos.x, y: currentPos.y + 1, z: currentPos.z };
        const dimension = player.dimension;
        const dimensionId = dimension.id;
        const holdingTorch = isHoldingTorch(player);

        const existingLight = playerLights.get(playerId);

        if (holdingTorch) {
            if (
                !existingLight ||
                !positionsEqual(existingLight.position, currentPos) ||
                existingLight.dimensionId !== dimensionId
            ) {
                // Solo actualiza si cambió de bloque o dimensión
                if (existingLight) {
                    const oldDim = world.getDimension(existingLight.dimensionId);
                    if (oldDim) {
                        removeLightBlock(oldDim, existingLight.position);
                        removeLightBlock(oldDim, { x: existingLight.position.x, y: existingLight.position.y + 1, z: existingLight.position.z });
                    }
                }
                // Coloca luz en la posición y arriba si es posible
                let placed = false;
                if (canPlaceLightBlock(dimension, currentPos)) {
                    placeLightBlock(dimension, currentPos);
                    placed = true;
                }
                if (canPlaceLightBlock(dimension, abovePos)) {
                    placeLightBlock(dimension, abovePos);
                    placed = true;
                }
                if (placed) {
                    playerLights.set(playerId, {
                        position: currentPos,
                        dimensionId: dimensionId,
                        ticksToRemove: -1
                    });
                } else {
                    playerLights.delete(playerId);
                }
            }
            // Si no cambió de bloque ni dimensión, no hace nada
        } else if (existingLight) {
            // Solo inicia el temporizador si no lo tenía
            if (existingLight.ticksToRemove === undefined) {
                existingLight.ticksToRemove = LIGHT_REMOVAL_DELAY;
            } else if (existingLight.ticksToRemove > 0) {
                existingLight.ticksToRemove--;
            } else {
                const dimension = world.getDimension(existingLight.dimensionId);
                if (dimension) {
                    removeLightBlock(dimension, existingLight.position);
                    removeLightBlock(dimension, { x: existingLight.position.x, y: existingLight.position.y + 1, z: existingLight.position.z });
                }
                playerLights.delete(playerId);
            }
        }
    }
}

function updateTorchTimers() {
    for (const player of world.getAllPlayers()) {
        const playerId = player.id;
        const holding = isHoldingTorchAny(player);
        let timer = torchTimers.get(playerId);
        if (holding) {
            if (!timer) {
                timer = { secondsLeft: TORCH_TIMER_SECONDS, active: true };
                torchTimers.set(playerId, timer);
                // Mensaje solo al activar por primera vez, usando 'me'
                player.runCommandAsync('me 10 minutes flashlight.');
            } else {
                if (!timer.active) {
                    // Mostrar mensaje al reanudar con segundos restantes
                    player.runCommandAsync(`me ${timer.secondsLeft} seconds flashlight.`);
                }
                timer.active = true;
            }
            if (timer.secondsLeft > 0) {
                timer.secondsLeft--;
            } else {
                // Se quedó sin batería
                // Reemplazar solo en la mano donde está la linterna
                const eq = player.getComponent("minecraft:equippable");
                if (eq) {
                    const main = eq.getEquipment("Mainhand");
                    const off = eq.getEquipment("Offhand");
                    if (main && main.typeId === TORCH_ID) {
                        player.runCommandAsync('replaceitem entity @s slot.weapon.mainhand 0 xaierg:linterna_apagada 1');
                    }
                    if (off && off.typeId === TORCH_ID) {
                        player.runCommandAsync('replaceitem entity @s slot.weapon.offhand 0 xaierg:linterna_apagada 1');
                    }
                }
                player.runCommandAsync('titleraw @s actionbar {"rawtext":[{"text":"Your flashlight ran out of battery!"}]}');
                torchTimers.delete(playerId);
            }
        } else if (timer && timer.active) {
            // Pausar el contador
            timer.active = false;
        }
    }
}


system.runInterval(updateDynamicTorchLight, 2); // Corre cada 2 ticks para menos carga
system.runInterval(updateTorchTimers, 20); // Cada segundo

world.afterEvents.playerLeave.subscribe(ev => removePlayerLightImmediate(ev.playerId));
world.afterEvents.entityDie.subscribe(ev => {
    if (ev.deadEntity.typeId === "minecraft:player") removePlayerLightImmediate(ev.deadEntity.id);
});

// Detectar uso de linterna apagada
world.afterEvents.itemUse.subscribe(ev => {
    const { itemStack, source } = ev;
    if (!itemStack || !source || !source.isValid()) return;
    if (itemStack.typeId !== TORCH_OFF_ID) return;
    // Buscar batería en inventario
    source.runCommandAsync('playsound flashlight.click @s');
    const inv = source.getComponent("minecraft:inventory");
    if (!inv) return;
    let batterySlot = -1;
    for (let i = 0; i < inv.container.size; i++) {
        const slot = inv.container.getItem(i);
        if (slot && slot.typeId === BATTERY_ID) {
            batterySlot = i;
            break;
        }
    }
    if (batterySlot !== -1) {
        // Quitar solo 1 batería
        const batteryItem = inv.container.getItem(batterySlot);
        if (batteryItem.amount > 1) {
            batteryItem.amount--;
            inv.container.setItem(batterySlot, batteryItem);
        } else {
            inv.container.setItem(batterySlot, undefined);
        }
        // Reemplazar linterna apagada solo en la mano donde está
        const eq = source.getComponent("minecraft:equippable");
        if (eq) {
            const main = eq.getEquipment("Mainhand");
            const off = eq.getEquipment("Offhand");
            if (main && main.typeId === TORCH_OFF_ID) {
                source.runCommandAsync('replaceitem entity @s slot.weapon.mainhand 0 xaierg:linterna 1');
            }
            if (off && off.typeId === TORCH_OFF_ID) {
                source.runCommandAsync('replaceitem entity @s slot.weapon.offhand 0 xaierg:linterna 1');
            }
        }
    } else {
        // Mostrar mensaje en rojo en actionbar
        source.runCommandAsync('titleraw @s actionbar {"rawtext":[{"text":"Missing battery!"}]}');
    }
});
