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

// === 1. Branch Groups ===

const BRANCH_GROUPS = {
    horror: {
        trigger: 'pu_biomes:horror_branch',
        types: [
            'pu_biomes:horror_curve_root',
            'pu_biomes:horror_deer_branch',
            'pu_biomes:horror_hand_branch',
            'pu_biomes:horror_leg_root',
            'pu_biomes:horror_root',
            'pu_biomes:horror_twisted_root',
            'pu_biomes:horror_wing_branch'
        ],
        stateMap: {
            'pu_biomes:horror_curve_root': ['minecraft:block_face'],
            'pu_biomes:horror_deer_branch': ['minecraft:block_face'],
            'pu_biomes:horror_hand_branch': ['minecraft:block_face', 'pu_biomes:upper_block_bit'],
            'pu_biomes:horror_leg_root': [], // no states
            'pu_biomes:horror_root': ['minecraft:block_face'],
            'pu_biomes:horror_twisted_root': [],
            'pu_biomes:horror_wing_branch': ['minecraft:block_face', 'pu_biomes:right_block_bit']
        }
    },
    toxic: {
        trigger: 'pu_biomes:toxic_branch',
        types: [
            'pu_biomes:toxic_branch',
            'pu_biomes:toxic_curve_root',
            'pu_biomes:toxic_deer_branch',
            'pu_biomes:toxic_twisted_root'
        ],
        stateMap: {
            'pu_biomes:toxic_branch': ['minecraft:block_face'],
            'pu_biomes:toxic_curve_root': ['minecraft:block_face'],
            'pu_biomes:toxic_deer_branch': ['minecraft:block_face'],
            'pu_biomes:toxic_twisted_root': ['minecraft:block_face']
        }
    }
};

// === 2. Utilities ===

function getSideBlock(block, face) {
    switch (face) {
        case 'north': return block.north();
        case 'south': return block.south();
        case 'east': return block.east();
        case 'west': return block.west();
        default: return null;
    }
}

function canPlaceDoubleBlockVertical(block) {
    return block.above().typeId === 'minecraft:air';
}

function canPlaceDoubleBlockHorizontal(block, blockFace) {
    const neighbor = getSideBlock(block, blockFace);
    return neighbor && neighbor.typeId === 'minecraft:air';
}

function getPlaceableBranches(groupKey, block) {
    const face = block.permutation.getState('minecraft:block_face');
    const group = BRANCH_GROUPS[groupKey];

    return group.types.filter(type => {
        if (type === 'pu_biomes:horror_hand_branch' || type === 'pu_biomes:horror_leg_root') {
            return canPlaceDoubleBlockVertical(block);
        }
        if (type === 'pu_biomes:horror_wing_branch') {
            return canPlaceDoubleBlockHorizontal(block, face);
        }
        return true;
    });
}

function tryResolvePermutation(type, face, extraStates = {}, stateMap) {
    const supportedStates = stateMap[type];
    const states = {};

    if (supportedStates.includes('minecraft:block_face')) {
        states['minecraft:block_face'] = face;
    }

    for (const [key, value] of Object.entries(extraStates)) {
        if (supportedStates.includes(key)) {
            states[key] = value;
        }
    }

    try {
        return BlockPermutation.resolve(type, states);
    } catch (err) {
        console.warn(`[BranchScript] Invalid permutation for "${type}" with states: ${JSON.stringify(states)}`);
        return null;
    }
}

// === 3. Main Logic ===

function handleBranchPlacement(event) {
    const { block } = event;

    for (const groupKey in BRANCH_GROUPS) {
        const group = BRANCH_GROUPS[groupKey];
        if (block.typeId !== group.trigger) continue;

        system.run(() => {
            const face = block.permutation.getState('minecraft:block_face');
            const validBranches = getPlaceableBranches(groupKey, block);
            if (validBranches.length === 0) return;

            const selectedType = validBranches[Math.floor(Math.random() * validBranches.length)];
            const basePerm = tryResolvePermutation(selectedType, face, {}, group.stateMap);
            if (!basePerm) return;

            block.setPermutation(basePerm);

            // === Special Handling (Horror Group Only) ===
            if (groupKey === 'horror') {
                if (selectedType === 'pu_biomes:horror_hand_branch') {
                    const upperPerm = tryResolvePermutation(
                        selectedType,
                        face,
                        { 'pu_biomes:upper_block_bit': true },
                        group.stateMap
                    );
                    const above = block.above();
                    if (upperPerm && above) above.setPermutation(upperPerm);
                }

                if (selectedType === 'pu_biomes:horror_leg_root') {
                    const above = block.above();
                    if (above) above.setPermutation(basePerm); // no upper_block_bit
                }

                if (selectedType === 'pu_biomes:horror_wing_branch') {
                    const sideBlock = getSideBlock(block, face);
                    const sidePerm = tryResolvePermutation(
                        selectedType,
                        face,
                        { 'pu_biomes:right_block_bit': true },
                        group.stateMap
                    );
                    if (sidePerm && sideBlock) sideBlock.setPermutation(sidePerm);
                }
            }
        });

        break; // Exit after first match
    }
}

world.afterEvents.playerPlaceBlock.subscribe(handleBranchPlacement);