// js/noise-toggle.js

import { Logger } from "../../core/logger.js";

export function init(config = {}) {
    Logger.log('Noise Toggle Init', config);

    const {
        selector = ".noise-overlay",
        toggleKey = "g",
        className = "grainy",
        enableTransition = true,
    } = config;

    const body = document.body;
    const noiseElement = document.querySelector(selector);

    if (!noiseElement) return;

    const isInput = noiseElement => ["input", "textarea"].includes(noiseElement.tagName.toLowerCase());

    function update() {
        if (enableTransition) {
            noiseElement.classList.toggle("hidden", !body.classList.contains(className));
        } else {
            noiseElement.style.display = body.classList.contains(className) ? "block" : "none";
        }
    }

    update();

    document.addEventListener("keydown", (e) => {
        if (
            e.key.toLowerCase() === toggleKey &&
            !e.ctrlKey && !e.metaKey && !e.altKey &&
            !isInput(e.target)
        ) {
            body.classList.toggle(className);
            update();
        }
    })
}
