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

const CRYSTAL_TYPES = [
    'amethyst', 'apatite', 'citrine', 'onyx', 'peridot',
    'ruby', 'sapphire', 'selenite', 'topaz'
];

const LAMP_TYPE_PREFIX = 'pu_biomes:';
const CRYSTAL_LAMP_IDS = new Set(CRYSTAL_TYPES.map(type => `${LAMP_TYPE_PREFIX}${type}_lamp`));

function isCrystalLamp(typeId) {
    return CRYSTAL_LAMP_IDS.has(typeId);
}

function updateLampSize(block, size) {
    const states = block.permutation.getAllStates();
    states['pu_biomes:size'] = size;
    const updatedPerm = BlockPermutation.resolve(block.typeId, states);
    block.setPermutation(updatedPerm);
}

function handleCrystalLampPlacement(event) {
    const { block } = event;
    if (!isCrystalLamp(block.typeId)) return;

    const below = block.below();
    if (below.typeId !== block.typeId) return;

    const belowSize = below.permutation.getState('pu_biomes:size');
    if (belowSize !== 'small') return;

    updateLampSize(below, 'bottom');
    updateLampSize(block, 'top');
}

world.afterEvents.playerBreakBlock.subscribe(event => {
    const { block } = event;

    const above = block.above();
    const below = block.below();

    if (isCrystalLamp(above.typeId)) {
        const size = above.permutation.getState('pu_biomes:size');
        if (size === 'top') updateLampSize(above, 'small');
    }

    if (isCrystalLamp(below.typeId)) {
        const size = below.permutation.getState('pu_biomes:size');
        if (size === 'bottom') updateLampSize(below, 'small');
    }
});

world.afterEvents.playerPlaceBlock.subscribe(handleCrystalLampPlacement);
