/**
 * @package     VP Prime Framework
 *
 * @author      Abhishek Das <info@virtueplanet.com>
 * @link        https://www.virtueplanet.com
 * @copyright   Copyright (C) 2023 Virtueplanet Services LLP. All Rights Reserved.
 * @license     GNU General Public License version 2 or later; see LICENSE.txt
 */

var Joomla = window.Joomla || {};
var PrimeProductCarousel = window.PrimeProductCarousel || {};

(function (module, Joomla, document, window) {
    module.setControlButton = function () {
        [].slice.call(document.querySelectorAll('.product-carousel-tns-outer')).forEach(function (carousel) {
            var height = carousel.querySelector('.tns-inner').offsetHeight;

            [].slice.call(carousel.querySelectorAll('.tns-controls button')).forEach(function (button) {
                button.style.top = (height / 2) + 'px';
            })
        })
    }

    module.checkRestartAutoplay = function (config, slider) {
        var info = slider.getInfo();

        setInterval(function () {
            if (slider.lastChanged && Date.now() - slider.lastChanged > config.autoplayTimeout && !info.container.matches(':hover')) {
                slider.play();
                slider.lastChanged = Date.now();
            }
        }, 500);
    }

    document.addEventListener('DOMContentLoaded', function () {
        var configs = Joomla.getOptions('vpprime.product.carousel', []);
        var options = {
            onInit: function (info) {
                info.container.closest('.tns-outer').classList.add('product-carousel-tns-outer');
                [].slice.call(info.container.querySelectorAll('img')).forEach(function (image) {
                    image.addEventListener('load', function () {
                        module.setControlButton();
                    })
                })
            }
        }

        if (Array.isArray(configs) && configs.length) {
            configs.forEach(function (config) {
                config = Object.assign({}, config, options);
                var slider = tns(config);

                slider.lastChanged = null;

                slider.events.on('indexChanged', function (info) {
                    slider.lastChanged = Date.now();
                });

                if (config.autoplay && !config.autoplayButtonOutput) {
                    module.checkRestartAutoplay(config, slider);
                }
            })
        }
    })

    window.addEventListener('resize', function () {
        module.setControlButton();
    })
})(PrimeProductCarousel, Joomla, document, window);