/**
 * WordPress dependencies
 */
import apiFetch from "@wordpress/api-fetch";

// Fall back to no-ops if the controls frontend bundle didn't load
// (e.g. blocked by a firewall/optimizer) so the carousel still initializes.
const ebFrontend = window.eb_frontend || {};
const generateArrowHTML = ebFrontend.generateArrowHTML || (() => "");
const loadSvgIcons = ebFrontend.loadSvgIcons || (() => {});

const rootURL = EssentialBlocksLocalize
    ? EssentialBlocksLocalize.rest_rootURL
    : false;
apiFetch.use(apiFetch.createRootURLMiddleware(rootURL));

/**
 * External dependencies
 */
// import Slider from "react-slick";

window.addEventListener("DOMContentLoaded", (event) => {
    const wrappers = document.getElementsByClassName(
        `eb-post-carousel-wrapper`,
    );

    for (let wrapper of wrappers) {
        const dataset = wrapper.dataset;
        let slider = dataset?.id;
        let settings = JSON.parse(dataset.slidersettings);
        let attributes = JSON.parse(dataset.attributes);

        let arrows = settings.arrows;
        let autoplay = settings.autoplay;
        let dots = settings.dots;
        let infinite = settings.infinite;
        let pauseOnHover = settings.pauseOnHover;
        let slideToShowRange = settings.slideToShowRange;
        let MOBslideToShowRange = settings.MOBslideToShowRange;
        let TABslideToShowRange = settings.TABslideToShowRange;
        let autoplaySpeed = settings.autoplaySpeed;
        let speed = settings.speed;
        let rtl = settings.isRTLEnable;

        const isRTL = document.documentElement.dir === "rtl";

        (function ($) {
            $(".init-" + slider).slick({
                arrows,
                autoplay,
                dots,
                infinite,
                pauseOnHover,
                slidesToShow: slideToShowRange,
                autoplaySpeed,
                speed,
                rtl: isRTL,
                prevArrow: generateArrowHTML(attributes.leftArrowIcon, 'prev'),
                nextArrow: generateArrowHTML(attributes.rightArrowIcon, 'next'),
                responsive: [
                    {
                        breakpoint: 1024,
                        settings: {
                            slidesToShow: TABslideToShowRange,
                        },
                    },
                    {
                        breakpoint: 767,
                        settings: {
                            slidesToShow: MOBslideToShowRange,
                        },
                    },
                ],
            });

            // Load SVG icons after slick initialization
            setTimeout(() => {
                loadSvgIcons(wrapper);
            }, 100);
        })(jQuery);
    }
});
