<?php
/**
 * Hyvä Themes - https://hyva.io
 * Copyright © Hyvä Themes 2020-present. All rights reserved.
 * This product is licensed per Magento install
 * See https://hyva.io/license
 */

declare(strict_types=1);

use Hyva\Theme\Model\ViewModelRegistry;
use Hyva\Theme\ViewModel\HeroiconsOutline;
use Hyva\Theme\ViewModel\Store;
use Magento\Framework\Escaper;
use Magento\Framework\View\Element\Template;
use Banyo\CustomHomePage\ViewModel\ThirdParty;

// phpcs:disable Generic.Files.LineLength.TooLong
/** @var ThirdParty $viewModel */
/** @var Template $block */
/** @var Escaper $escaper */
/** @var ViewModelRegistry $viewModels */
/** @var Store $viewModelStore */

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$viewModel = $objectManager->get(Banyo\CustomHomePage\ViewModel\ThirdParty::class);

/** @var ThirdParty $viewModel */
$viewModel = $viewModels->require(ThirdParty::class);
$heading = $viewModel->getConfigValue('brands_section/brands_section_title');

$viewModelStore = $viewModels->require(Store::class);

/** @var HeroiconsOutline $heroicons */
$heroicons = $viewModels->require(HeroiconsOutline::class);

$title = (string) $block->getTitle();
$items = $block->getItems() ?? [];
if (is_object($items) && $items instanceof Iterator) {
    $items = iterator_to_array($items);
}
if (!$itemCount = count($items)) {
    return '';
}
$sliderItemRenderer = $block->getChildBlock('slider.item.template');

?>
<script>
    'use strict';

    function initBrandSliderComponent() {
        return {
            active: 0,
            itemCount: 0,
            isAutoplay: <?= (int)$block->getData('is_autoplay') ?>,
            autoplayInterval: <?= (int)$block->getData('autoplay_interval') ?>,
            isAutoplayLoop: <?= (int)$block->getData('is_autoplay_loop') ?>,
            pauseOnHover: <?= (int)$block->getData('pause_on_hover') ?>,
            interval: null,
            slider: null,
            getSlider() {
                if (!this.slider) {
                    this.slider = this.$el.querySelector('.js_slides');
                }

                return this.slider;
            },
            pageSize: 4,
            pageFillers: 0,
            calcPageSize() {
                const slider = this.getSlider();
                if (slider) {
                    this.itemCount = slider.querySelectorAll('.js_slide').length;
                    this.pageSize = Math.round(slider.clientWidth / slider.querySelector('.js_slide').clientWidth);
                    this.pageFillers = (
                        this.pageSize * Math.ceil(this.itemCount / this.pageSize)
                    ) - this.itemCount;
                }

                // autoplay
                this.startAutoplay()
            },
            calcActive() {
                const slider = this.getSlider();
                if (slider) {
                    const sliderItems = this.itemCount + this.pageFillers;
                    const calculatedActiveSlide = slider.scrollLeft / (slider.scrollWidth / sliderItems);
                    this.active = Math.round(calculatedActiveSlide / this.pageSize) * this.pageSize;
                }
            },
            scrollPrevious() {
                this.scrollTo(this.active - this.pageSize);
            },
            scrollNext() {
                this.scrollTo(this.active + this.pageSize);
            },
            scrollTo(idx) {
                const slider = this.getSlider();
                if (slider) {
                    const slideWidth = slider.scrollWidth / (this.itemCount + this.pageFillers);
                    slider.scrollLeft = Math.floor(slideWidth) * idx;
                    this.active = idx;

                    this.resetAutoplay();
                }
            },
            startAutoplay() {
                if (
                    !this.isAutoplay
                    || this.interval
                    || (!this.isAutoplayLoop && this.active === this.pageSize)
                ) {
                    return;
                }

                this.interval = setInterval(function () {
                    const self = this;

                    if (self.active < self.pageSize) {
                        self.scrollNext();
                    } else if (this.isAutoplayLoop) {
                        self.scrollTo(0);
                    } else {
                        clearInterval(self.interval);
                        self.interval = null;
                    }
                }.bind(this), this.autoplayInterval);
            },
            stopAutoplay() {
                if (this.pauseOnHover) {
                    clearInterval(this.interval);
                    this.interval = null;
                }
            },
            resetAutoplay() {
                if (this.interval) {
                    clearInterval(this.interval);
                    this.interval = null;
                }

                this.startAutoplay();
            }
        }
    }
</script>
<section class="2xl:container mx-auto px-3 3xl:max-w-screen-2xl "
         x-data="initBrandSliderComponent()"
         x-init="calcPageSize();"
         @resize.window.debounce="calcPageSize(); $nextTick( function() { calcActive() })"
         @mouseover="stopAutoplay()"
         @mouseout="startAutoplay()"
>
    <?php if ($items): ?>
        <div class="relative">
            <?php if ($heading): ?>
                <div>
                    <h3 class="text-xl lg:text-3xl font-bold font-sen text-black my-4">
                        <?= $escaper->escapeHtml($heading); ?>
                    </h3>
                </div>
            <?php endif; ?>
            <div>
                <div class="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-6 items-center overflow-auto  gap-4 pt-4"
                     @scroll.debounce="calcActive"
                >
                    <?php foreach ($items as $item): ?>
                        <div >
                            <div class="bg-white rounded-2xl overflow-hidden shadow-md mb-4 p-1">
                                <?= $sliderItemRenderer->setItem($item)->toHtml() ?>
                            </div>
                        </div>
                    <?php endforeach; ?>
                </div>
            </div>
            <div>
                <template x-if="itemCount > pageSize">
                    <div class="flex items-center justify-center py-4">
                        <button
                            aria-label="<?= $escaper->escapeHtml(__('Previous')) ?>"
                            tabindex="-1"
                            class="mr-4 text-black rounded-full outline-none focus:outline-none flex-none"
                            :class="{ 'opacity-25 pointer-events-none _inactive' : active === 0 }"
                            @click="scrollPrevious">
                            <?= $heroicons->chevronLeftHtml("w-5 h-5", 25, 25) ?>
                        </button>
                        <div class="flex flex-wrap w-full md:w-auto justify-center">
                            <?php for ($i=0; $i < $itemCount; $i++): ?>
                                <span class="flex-shrink-0 block w-3 h-3 m-1 bg-black bg-opacity-25 rounded-full shadow cursor-pointer"
                                      :class="{
                                    'bg-opacity-100 _active': active === <?= (int) $i ?>,
                                    'hidden': (pageSize !== 1 && !!(<?= (int) $i ?> % pageSize))
                                    }"
                                      @click="scrollTo(<?= (int) $i ?>)">
                        </span>
                            <?php endfor; ?>
                        </div>
                        <button
                            aria-label="<?= $escaper->escapeHtml(__('Next')) ?>"
                            tabindex="-1"
                            class="ml-4 text-black rounded-full outline-none focus:outline-none flex-none"
                            :class="{ 'opacity-25 pointer-events-none _inactive' : active >= itemCount-pageSize }"
                            @click="scrollNext">
                            <?= $heroicons->chevronRightHtml("w-5 h-5", 25, 25) ?>
                        </button>
                    </div>
                </template>
            </div>
            <div class="flex justify-center text-red text-base lg:text-lg font-semibold underline lg:absolute top-0 right-0">
                <a href="/brands.html">View All</a>
            </div>
        </div>
    <?php endif; ?>
</section>
