const initTogglers = () => {
    const triggers = document.querySelectorAll('.sh-trig');
    for (const trigger of triggers) {
        toggler(trigger, { slide: true });
    }

    const showMoreTriggers = document.querySelectorAll('.show-more');
    for (const trigger of showMoreTriggers) {
        toggler(trigger, { hideTrigger: true });
    }
};

const toggler = (trigger, customSettings) => {
    function scrollToContent (content) {
        content.scrollIntoView();
    }

    function scrollToTrigger (trigger) {
        trigger.scrollIntoView();
    }

    const defaultSettings = {
        hideTrigger: false,
        slide: false,
        scrollToContent: false
        // offsetScroll: 0,
    };
    const settings = Object.assign(defaultSettings, customSettings);

    const content = document.querySelector('#' + trigger.getAttribute('data-content'));
    const textLess = trigger.getAttribute('data-less');
    const textMore = trigger.getAttribute('data-more');

    const isCheckbox = trigger.type && trigger.type === 'checkbox';
    const event = isCheckbox ? 'change' : 'click';

    trigger.addEventListener(event, (e) => {
        e.preventDefault();

        let toOpen = false;
        if (isCheckbox) {
            toOpen = trigger.checked === true;
        } else {
            toOpen = !content.classList.contains('sh-content--active');
        }

        if (trigger.classList.contains('sh-trig--active')) {
            trigger.setAttribute('aria-expanded', 'true');
        } else {
            trigger.setAttribute('aria-expanded', 'false');
        }

        if (toOpen) {
            content.animIn();
            if (settings.scrollToContent) {
                scrollToContent(content);
            }

            trigger.classList.add('sh-trig--active');
            trigger.setAttribute('aria-expanded', 'true');

            if (textLess) {
                trigger.innerHtml = textLess;
            }

            if (settings.hideTrigger) {
                trigger.hide();
            }
        } else {
            content.animOut();
            if (settings.scrollToContent) {
                scrollToTrigger(trigger);
            }

            trigger.classList.remove('sh-trig--active');
            trigger.setAttribute('aria-expanded', 'false');

            if (textMore) {
                trigger.innerHtml = textMore;
            }

            if (settings.hideTrigger) {
                trigger.show(settings.hideSpeed);
            }
        }
        return false;
    });

    if (isCheckbox) {
        trigger.dispatchEvent(new Event('change'));
    }
};

HTMLElement.prototype.hide = function () {
    this.style.display = 'none';
}

HTMLElement.prototype.show = function () {
    this.style.display = '';
}

HTMLElement.prototype.animIn = function () {
    this.classList.add('sh-content--active');
}

HTMLElement.prototype.animOut = function () {
    this.classList.remove('sh-content--active');
}

export { initTogglers };
