import { BlockPoweredEvent } from "../../Block Events/redstone";

// Sound mapping for trapdoor types
const trapdoorSounds = {
    "gs_cb:burnt_trapdoor": { open: "open.wooden_trapdoor", close: "close.wooden_trapdoor" },
    "gs_cb:charred_burnt_trapdoor": { open: "open.wooden_trapdoor", close: "close.wooden_trapdoor" },
    "gs_cb:smoldering_burnt_trapdoor": { open: "open.wooden_trapdoor", close: "close.wooden_trapdoor" },
    "gs_cb:sungrove_trapdoor": { open: "open.wooden_trapdoor", close: "close.wooden_trapdoor" }
    // Add more trapdoor types as needed
};

const powerEvent = new BlockPoweredEvent("gs_cb:powered", {
    onPower({ block, dimension }) {
        playTrapdoorSound(block, dimension);
    },
    onUnpowered({ block, dimension }) {
        playTrapdoorSound(block, dimension);
    }
});

function playTrapdoorSound(block, dimension) {
    const blockId = block.typeId;
    const sounds = trapdoorSounds[blockId] || { open: "default.open", close: "default.close" }; // Fallback sounds

    const isOpen = block.permutation.getState("gs_cb:open");
    const sound = isOpen ? sounds.close : sounds.open;

    // Customize pitch and volume for specific sounds
    const options = sound === "random.anvil_land"
        ? { pitch: 1.4, volume: 0.2 }
        : { pitch: 0.9, volume: 0.9 };

    block.setPermutation(block.permutation.withState("gs_cb:open", !isOpen));
    dimension.playSound(sound, block.center(), options);
}

export const CustomTrapdoorBlockComponent = {
    onPlayerInteract({ block, dimension }) {
        playTrapdoorSound(block, dimension);
    },
    onTick({ block, dimension }) {
        powerEvent.tick(block, dimension);
    }
};
