/**
 * audace/production — front-end controller. Fade-stacked slides with prev/next.
 */
(function () {
    'use strict';

    function init(root) {
        var stage  = root.querySelector('.audace-production__stage');
        if (!stage) return;
        var slides = Array.prototype.slice.call(stage.querySelectorAll('.audace-production__slide'));
        if (slides.length < 1) return;
        var prevButtons = Array.prototype.slice.call(root.querySelectorAll('.audace-production__arrow--prev'));
        var nextButtons = Array.prototype.slice.call(root.querySelectorAll('.audace-production__arrow--next'));
        var loop   = root.dataset.loop === '1';

        var active = 0;
        layout(active);

        function layout(to) {
            slides.forEach(function (p, i) {
                var on = i === to;
                p.classList.toggle('is-active', on);
                p.setAttribute('aria-hidden', on ? 'false' : 'true');
            });
            root.dataset.active = String(to);
        }

        function go(toRaw) {
            var n = slides.length;
            var to = loop ? ((toRaw % n) + n) % n : Math.max(0, Math.min(n - 1, toRaw));
            if (to === active) return;
            active = to;
            layout(to);
            updateArrows();
        }

        function updateArrows() {
            if (loop) return;
            prevButtons.forEach(function (b) { b.toggleAttribute('disabled', active === 0); });
            nextButtons.forEach(function (b) { b.toggleAttribute('disabled', active === slides.length - 1); });
        }

        function flashPressed(b) {
            b.classList.add('is-pressed');
            setTimeout(function () { b.classList.remove('is-pressed'); }, 300);
        }

        prevButtons.forEach(function (b) { b.addEventListener('click', function () { flashPressed(b); go(active - 1); }); });
        nextButtons.forEach(function (b) { b.addEventListener('click', function () { flashPressed(b); go(active + 1); }); });

        root.addEventListener('keydown', function (e) {
            if (e.target.closest('input, textarea, [contenteditable]')) return;
            if (e.key === 'ArrowRight') { e.preventDefault(); go(active + 1); }
            else if (e.key === 'ArrowLeft')  { e.preventDefault(); go(active - 1); }
        });

        updateArrows();
    }

    function boot() {
        document.querySelectorAll('.audace-production').forEach(init);
    }

    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', boot);
    } else {
        boot();
    }
})();
