import { system, world, BlockPermutation, Direction, ItemStack } from '@minecraft/server';

// Diccionario de direcciones cardinales para izquierda/derecha
const cardinalSides = {
    north: { left: 'west', right: 'east' },
    south: { left: 'east', right: 'west' },
    west: { left: 'south', right: 'north' },
    east: { left: 'north', right: 'south' }
};

// Función para obtener dirección opuesta
function getOppositeDirection(direction) {
    switch (direction) {
        case Direction.Up: return Direction.Down;
        case Direction.Down: return Direction.Up;
        case Direction.North: return Direction.South;
        case Direction.South: return Direction.North;
        case Direction.East: return Direction.West;
        case Direction.West: return Direction.East;
        default: return direction;
    }
}

// Función para decrementar el stack del jugador (opcional)
function decrementStack(player) {
    if (player.getGameMode() === 'creative') return;
    let inventory = player.getComponent('inventory').container;
    let item = inventory.getItem(player.selectedSlotIndex);
    if (!item) return;
    if (item.amount === 1) inventory.setItem(player.selectedSlotIndex, undefined);
    else inventory.setItem(player.selectedSlotIndex, new ItemStack(item.typeId, item.amount - 1));
}

// Registro del componente personalizado
world.beforeEvents.worldInitialize.subscribe(event => {
    event.blockComponentRegistry.registerCustomComponent('pa:puerta', {

        onPlayerInteract: e => {
            const { block } = e;
            const isOpen = block.permutation.getState('pa:is_open');
            const halfDoor = (block.permutation.getState('pa:part') === 'lower') ? block.above() : block.below();

            // Cambiar estado de la puerta
            block.setPermutation(block.permutation.withState('pa:is_open', !isOpen));
            if (halfDoor?.permutation.matches(block.typeId))
                halfDoor.setPermutation(halfDoor.permutation.withState('pa:is_open', !isOpen));

            // Reproducir sonido de apertura/cierre
            const sound = isOpen ? 'block.wooden_door.close' : 'block.wooden_door.open';
            block.dimension.playSound(sound, block.location, { pitch: 1, volume: 0.5 });
        },

        beforeOnPlayerPlace: e => {
            const { block, permutationToPlace } = e;
            const aboveBlock = block.above();
            if (!aboveBlock.isAir && !aboveBlock.isLiquid) {
                e.cancel = true;
                return;
            }

            const cardinalDirection = permutationToPlace.getState('minecraft:cardinal_direction');
            const sides = cardinalSides[cardinalDirection] || { left: 'north', right: 'south' };
            const leftBlock = block[sides.left]();
            const rightBlock = block[sides.right]();

            const doorStates = {
                'minecraft:cardinal_direction': cardinalDirection,
                'pa:side': 'left'
            };

            // Ajuste según bloques a los lados
            if ((leftBlock?.permutation.matches(permutationToPlace.type.id) && !rightBlock?.permutation.matches(permutationToPlace.type.id)) ||
                (rightBlock?.isSolid)) {
                doorStates['pa:side'] = 'right';
            }

            // Establecer permutación superior e inferior
            const lowerPerm = BlockPermutation.resolve(permutationToPlace.type.id, doorStates).withState('pa:part', 'lower');
            const upperPerm = BlockPermutation.resolve(permutationToPlace.type.id, doorStates).withState('pa:part', 'upper');

            e.permutationToPlace = lowerPerm;
            aboveBlock.setPermutation(upperPerm);
        },

        // Redstone check cada tick
        tick: block => {
            const isPowered = block.dimension.getRedstonePower(block.location) > 0;
            const isOpen = block.permutation.getState('pa:is_open');
            const halfDoor = (block.permutation.getState('pa:part') === 'lower') ? block.above() : block.below();

            if (isPowered !== isOpen) {
                block.setPermutation(block.permutation.withState('pa:is_open', isPowered));
                if (halfDoor?.permutation.matches(block.typeId))
                    halfDoor.setPermutation(halfDoor.permutation.withState('pa:is_open', isPowered));
            }
        }
    });
});

// Registrar tick global para actualizar todas las puertas con redstone
system.runInterval(() => {
    for (const dimension of world.getDimensions()) {
        for (const door of dimension.getBlocks({ type: 'pa:puerta' })) {
            if (door) door.components['pa:puerta']?.tick(door);
        }
    }
}, 2); // cada 2 ticks