(function () {

    const tiles = document.getElementsByClassName('tile');
    const figures = document.getElementsByClassName('work-item');
    var dialog = document.getElementById('dialog-image-modal');
    var image = document.getElementById('modal-image');
    var closeButton = document.getElementById('close-modal');
    var prevButton = document.getElementById('img-prev');
    var nextButton = document.getElementById('img-next');

    function saveImageIndex(work, variant) {
        dialog.dataset.work = work.toString();
        dialog.dataset.variant = variant.toString();
    };
    function updateImage(work, variant) {
        saveImageIndex(work, variant);
        const figure = figures[work];
        const option = figure.lastElementChild.children[variant];
        image.src = option.value;
    };
    function imgPrev() {
        var work = Number.parseInt(dialog.dataset.work);
        var variant = Number.parseInt(dialog.dataset.variant) - 1;
        if (variant < 0) {
            work -= 1;
            if (work < 0) {
                work = figures.length - 1;
            }
            const datalist = figures[work].lastElementChild;
            variant = datalist.children.length - 1;
        }
        updateImage(work, variant);
    };
    function imgNext() {
        var work = Number.parseInt(dialog.dataset.work);
        var variant = Number.parseInt(dialog.dataset.variant) + 1;
        const datalist = figures[work].lastElementChild;
        if (variant >= datalist.children.length) {
            work += 1;
            if (work >= figures.length) {
                work = 0;
            }
            variant = 0;
        }
        updateImage(work, variant);
    };
    function imgClose() {
        dialog.close();
        dialog.className = "hidden"; // nedded for safari :man_shrugging:
    };

    for (var i = 0; i < tiles.length; i++) {
        (function (workIndex) {
            tiles[workIndex].addEventListener('click', function () {
                updateImage(workIndex, 0);
                dialog.showModal();
                dialog.className = "";
            });
        })(i);
    }
    document.addEventListener('keydown', function (ev) {
        if (dialog.open) {
            switch (ev.key) {
                case "ArrowLeft":
                    imgPrev();
                    break;
                case "ArrowRight":
                    imgNext();
                    break;
                case "Escape":
                    imgClose();
                    break;
                default:
                    return;
            }
        }
    })
    prevButton.addEventListener('click', imgPrev);
    nextButton.addEventListener('click', imgNext);
    closeButton.addEventListener('click', imgClose);
})();
