/*
 * FiveCord — a Discord client mod
 * Copyright (c) 2025 FiveCord
 * SPDX-License-Identifier: GPL-3.0-or-later
 */

import { Devs } from "@utils/constants";
import definePlugin, { OptionType } from "@utils/types";

const sounds = {
    click1: new Audio("https://github.com/HypedDomi/FiveCord-Plugins/raw/main/Keyboard-Sounds/sounds/click1.wav"),
    click2: new Audio("https://github.com/HypedDomi/FiveCord-Plugins/raw/main/Keyboard-Sounds/sounds/click2.wav"),
    click3: new Audio("https://github.com/HypedDomi/FiveCord-Plugins/raw/main/Keyboard-Sounds/sounds/click3.wav"),
    backspace: new Audio("https://github.com/HypedDomi/FiveCord-Plugins/raw/main/Keyboard-Sounds/sounds/backspace.wav")
};

const ignoredKeys = ["CapsLock", "ShiftLeft", "ShiftRight", "ControlLeft", "ControlRight", "AltLeft", "AltRight", "MetaLeft", "MetaRight", "ArrowUp", "ArrowRight", "ArrowLeft", "ArrowDown", "MediaPlayPause", "MediaStop", "MediaTrackNext", "MediaTrackPrevious", "MediaSelect", "MediaEject", "MediaVolumeUp", "MediaVolumeDown", "AudioVolumeUp", "AudioVolumeDown"];

const keydown = (e: KeyboardEvent) => {
    if (ignoredKeys.includes(e.code)) return;
    for (const sound of Object.values(sounds)) sound.pause();
    if (e.code === "Backspace") {
        sounds.backspace.currentTime = 0;
        sounds.backspace.play();
    } else {
        const click = sounds[`click${Math.floor(Math.random() * 3) + 1}`];
        click.currentTime = 0;
        click.play();
    }
};

export default definePlugin({
    name: "Keyboard Sounds",
    description: "Adds the Opera GX Keyboard Sounds to Discord",
    authors: [Devs.FiveCord],
    start: () => document.addEventListener("keydown", keydown),
    stop: () => document.removeEventListener("keydown", keydown),
    options: {
        volume: {
            description: "Volume",
            type: OptionType.SLIDER,
            markers: [0, 100],
            stickToMarkers: false,
            default: 100,
            onChange: value => { for (const sound of Object.values(sounds)) sound.volume = value / 100; }
        }
    }
});
