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');

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

        if (!content.classList.contains('sh-content--active')) {
            content.animIn();
            if (settings.scrollToContent) {
                scrollToContent(content);
            }

            trigger.classList.add('sh-trig--active');
            if (textLess) {
                trigger.innerHtml = textLess;
            }

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

            trigger.classList.remove('sh-trig--active');
            if (textMore) {
                trigger.innerHtml = textMore;
            }

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

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

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

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

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

export { initTogglers };
