// reverb.js

(function() {
    let reverbEnabled = false;
    let convolver = null;
    let currentIR = null;
    let audioContext = null;

    // Initialize reverb with the plugin's audio context
    function initReverb(ctx) {
        audioContext = ctx;
        convolver = audioContext.createConvolver();
    }

    // Load an IR file (fetch & decode)
    function loadReverb(irUrl) {
        if (!audioContext || !irUrl) return;

        // Skip reload if same IR
        if (currentIR === irUrl) return;

        fetch(irUrl)
            .then(response => response.arrayBuffer())
            .then(arrayBuffer => audioContext.decodeAudioData(arrayBuffer))
            .then(audioBuffer => {
                convolver.buffer = audioBuffer;
                currentIR = irUrl;
            })
            .catch(err => console.error("Error loading IR:", err));
    }

    // Enable or disable reverb
    function setReverbEnabled(enabled) {
        reverbEnabled = enabled;
    }

    // Connect a source to reverb (or directly to analyser if disabled)
    function applyReverb(sourceNode, analyserNode) {
        // Always connect the dry signal path
        sourceNode.connect(analyserNode);

        // Connect the wet reverb path if enabled and convolver is ready
        if (reverbEnabled && convolver && convolver.buffer) {
            sourceNode.connect(convolver);
            convolver.connect(analyserNode);
        }
    }

    function isEnabled() {
        return reverbEnabled;
    }

    // DOM events for checkbox + IR select
	document.addEventListener('DOMContentLoaded', () => {
		const irCheckbox = document.getElementById('ptpian_reverb_enable');
		const irSelect = document.getElementById('ptpian_reverb_ir');

		if (irCheckbox) {
            // Initialize from current checkbox value on load
            setReverbEnabled(irCheckbox.checked);
            if (irCheckbox.checked && irSelect && irSelect.value) {
                const irUrl = ptpianReverbData?.irs?.[irSelect.value];
                loadReverb(irUrl);
            }

			irCheckbox.addEventListener('change', () => {
				setReverbEnabled(irCheckbox.checked);

				if (irCheckbox.checked && irSelect && irSelect.value) {
					const irUrl = ptpianReverbData?.irs?.[irSelect.value];
					loadReverb(irUrl);
				}
			});
		}

		if (irSelect) {
			irSelect.addEventListener('change', () => {
				if (irCheckbox && irCheckbox.checked && irSelect.value) {
					const irUrl = ptpianReverbData?.irs?.[irSelect.value];
					loadReverb(irUrl);
				}
			});
		}
	});


    // Export functions to global object
    window.ptpReverb = {
        initReverb,
        loadReverb,
        setReverbEnabled,
        applyReverb,
        isEnabled
    };
})();
