/**
 * Tab as steps
 */
import IGDATAPOOLFE from '@dp/ig_datapool_fe.js';

const stepButtonPlugin = {
    initFields(form) {
        this.init(form);
    },
    init(form) {
        const formEl = form instanceof HTMLElement ? form : document.querySelector(form);
        this.form = formEl;

        const stepInput = formEl.querySelector('input.currentStep');
        if (!stepInput) return;

        let currentStep = parseInt(stepInput.value, 10) || 0;

        // Previous step button
        formEl.querySelectorAll('.dp-button-prevStep').forEach((btn) => {
            btn.addEventListener('click', (e) => {
                e.preventDefault();
                stepInput.value = currentStep - 1;
                const formToSubmit = formEl.querySelector('form') || formEl;
                formToSubmit.submit();
            });
        });

        // Next step button
        formEl.querySelectorAll('.dp-button-nextStep').forEach((btn) => {
            btn.addEventListener('click', (e) => {
                e.preventDefault();
                stepInput.value = currentStep + 1;
                const formToSubmit = formEl.querySelector('form') || formEl;
                formToSubmit.submit();
            });
        });
    }
};
IGDATAPOOLFE.addPlugin('stepButton', stepButtonPlugin);

export default stepButtonPlugin;
