import { onPageLoadComplete } from '@nimius/event-utility';

/*
 * <input type="number" data-reveal="[data-age-group]">
 *
 * <div data-age-group>
 *     <select name="age_child1"></select>
 * </div>
 * <div data-age-group>
 *     <select name="age_child1"></select>
 * </div>
 * <div data-age-group>
 *     <select name="age_child1"></select>
 * </div>
 * <div data-age-group>
 *     <select name="age_child1"></select>
 * </div>
 */

onPageLoadComplete(() => {
    for (const input of document.querySelectorAll('[data-reveal]')) {
        const selector = input.getAttribute('data-reveal');
        const elements = [...document.querySelectorAll(selector)];
        const parents = elements.map(el => el.parentNode);

        /**
         * Event Listener that will be executed
         * on every change of the input.
         */
        const listener = () => {
            // Remove all from DOM.
            for (const element of elements) {
                if (element.parentNode) {
                    element.parentNode.removeChild(element);
                }
            }

            // Insert first n elements back into DOM.
            for (let i = 0; i < input.value; i++) {
                if (i >= elements.length) {
                    continue;
                }
                parents[i].appendChild(elements[i]);
            }
        };

        // Attach event listener.
        input.addEventListener('change', listener);
        input.addEventListener('input', listener);
        listener();
    }
});
