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

// Configuration for different furniture types
const FURNITURE_CONFIG = {
    "bathtub": { yOffset: 0.0 },
    "float_lounger": { yOffset: 0.0 },
    "rocking_chair": { yOffset: 0.45 },
    "stool": { yOffset: 0.30 },
    "sun_lounger": { yOffset: 0.23 },
    "bench": { yOffset: 0.23 },
    "sofa": { yOffset: 0.23 },
    "couch": { yOffset: 0.23 },
    "chair": { yOffset: 0.4 }
};

// Helper function to get furniture type and offset
function getFurnitureConfig(blockId) {
    // Check for exact match first
    if (FURNITURE_CONFIG[blockId]) {
        return { type: blockId, ...FURNITURE_CONFIG[blockId] };
    }
    
    // Check for partial matches
    for (const [key, config] of Object.entries(FURNITURE_CONFIG)) {
        if (blockId.includes(key)) {
            return { type: key, ...config };
        }
    }
    
    return null;
}

// Helper function to create sitting entity
function createSittingEntity(block, player, yOffset) {
    const location = block.location;
    const ride_location = { 
        x: location.x + 0.5, 
        y: location.y + yOffset, 
        z: location.z + 0.5 
    };
    
    const ride = block.dimension.spawnEntity("dss:sitting", ride_location);
    
    // Update block state
    let newPermutation = BlockPermutation.resolve(block.typeId, {
        ...block.permutation.getAllStates(),
        'dss:sitting': true
    });
    block.setPermutation(newPermutation);
    
    // Add player as rider
    const addrider = ride.getComponent("rideable");
    addrider.addRider(player);
}

// Helper function to check and remove sitting entity
function checkAndRemoveSittingEntity(block, yOffset) {
    const location = block.location;
    const ride_location = { 
        x: location.x + 0.5, 
        y: location.y + yOffset, 
        z: location.z + 0.5 
    };
    
    try {
        const ride = block.dimension.getEntities({ 
            type: 'dss:sitting', 
            location: ride_location, 
            maxDistance: 0.1 
        });

        for (const entity of ride) {
            const despawn = entity.getComponent("is_stunned");
            if (despawn) {
                let newPermutation = BlockPermutation.resolve(block.typeId, {
                    ...block.permutation.getAllStates(),
                    'dss:sitting': false
                });
                block.setPermutation(newPermutation);
                return true;
            }
        }
    } catch (error) {
        // Handle any errors silently
    }
    
    return false;
}

const RideComponent = {
    onPlayerInteract(event) {
        const { block, player } = event;
        const block_ride = block.permutation.getState('dss:sitting');

        // Only proceed if the block is not already being sat on
        if (block_ride === false) {
            const config = getFurnitureConfig(block.typeId);
            if (config) {
                createSittingEntity(block, player, config.yOffset);
            }
        }
    },
    
    onTick(event) {
        const { block } = event;
        const block_ride = block.permutation.getState('dss:sitting');
        
        // Only check blocks that are being sat on
        if (block_ride === true) {
            const config = getFurnitureConfig(block.typeId);
            if (config) {
                checkAndRemoveSittingEntity(block, config.yOffset);
            }
        }
    }
};

world.afterEvents.playerBreakBlock.subscribe((event) => {
    const { block } = event;
    const block_ride = block.permutation.getState('dss:sitting');
    if (block_ride === true) {
        block.setPermutation(BlockPermutation.resolve(block.typeId, { 'dss:sitting': false }));
    }
    const location = block.location;
    const ride_location = { 
        x: location.x + 0.5, 
        y: location.y + 0.5, 
        z: location.z + 0.5 
    };

    const rideEntities = block.dimension.getEntities({ 
        type: 'dss:sitting', 
        location: ride_location 
    });

    rideEntities.forEach(ride => {
        ride.remove(); // Remove the sitting entity
    });
});

world.beforeEvents.worldInitialize.subscribe(({ blockComponentRegistry }) => {
    blockComponentRegistry.registerCustomComponent("dss:sittings", RideComponent);
});