<?php
$document = JFactory::getDocument();
$lang = JFactory::getLanguage();
$langCode = $lang->getTag();
$langCodeShort = substr($langCode, 0, 2);

$model = $this->params->get('model', 'tracktorpool_products');

$uid = bin2hex(random_bytes(10));

$ua = htmlentities($_SERVER['HTTP_USER_AGENT'], ENT_QUOTES, 'UTF-8');
$IE = (preg_match('~MSIE|Internet Explorer~i', $ua) || (strpos($ua, 'Trident/7.0; rv:11.0') !== false))? 1 : 0;

$script = "
'use strict';

function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } }

document.addEventListener('DOMContentLoaded', function (event) {
	var app = new Vue({
		el: '#app-$uid',
		data: {
			hovered: false,
			showProduct: null,
			width: 0,
			boxWidth: 1,
			wrapperWidth: 1,
			ie11: {$IE},
			initialized: false,
			speed: {$this->params->get('speed', '750')},
			boxPosition: {
				x: 0,
				y: 0
			},
			products: ". json_encode(array_splice($this->ads, 0, $this->params->get('limit', 10))) .",
			filters: {
				manufacturer: false,
				category: false,
				age: false
			},
			sortKey: 'id',
			sortOrders: {
				id: 1,
				year: 1,
				price: 1,
				workhours: 1,
				trade_price: 1,
				power: 1
			}
		},
		watch: {
			filteredData: function filteredData() {
				this.calculateSize();
			}
		},
		methods: {
		  formatPrice: function formatPrice(value) {
        return value.toLocaleString('de-DE', { style: 'currency', currency: 'EUR',currencyDisplay: 'code', minimumFractionDigits:2, maximumFractionDigits: 2 });
      },
			hover: function hover(hovering, product) {
				this.hovered = hovering;
				// this.showProduct = (hovering) ? product : null;
				this.showProduct = product;
			},
			moveBox: function moveBox(e) {
				// const target = e.target || e.srcElement;
				var rect = this.\$el.getBoundingClientRect();
				this.boxPosition = {
					x: e.clientX - rect.left,
					y: e.clientY - rect.top
				};
			},
			calculateSize: function calculateSize() {
			    var margin = parseInt(getComputedStyle(this.\$refs.carousel.firstElementChild).marginRight);
				this.boxWidth = this.\$refs.carousel.firstElementChild.clientWidth + margin;
				this.wrapperWidth = this.\$refs.carousel.parentElement.clientWidth;
				this.width = this.boxWidth * this.filteredData.length;
			}
		},
		created: function created() {},
		mounted: function mounted() {
		    var _this1 = this;
			document.addEventListener('resize', this.calculateSize);
			this.calculateSize();

			if (this.ie11) {
                setTimeout(function(){
                    _this1.initialized = true;
                }, 3000);
			} else {
			    this.initialized = true;
			}
		},
    filters: {
      sprintf: sprintf,
    },
		computed: {
			filteredData: function filteredData() {
				var _this = this;
				var sortKey = this.sortKey;
				var order = this.sortOrders[sortKey] || 1;
				var filtered = this.products;

				filtered = filtered.sort(function (a, b) {
					if (['price', 'workhours', 'trade_price', 'power'].includes(sortKey)) {
						return Math.sign((b[sortKey] ? b[sortKey].value : -1) - (a[sortKey] ? a[sortKey].value : -1)) * order;
					}
					return Math.sign(b[sortKey] - a[sortKey]) * order;
				});

				var count = Math.max(2, Math.ceil((this.wrapperWidth * 2) / (this.boxWidth * filtered.length)));
				return new Array(count).fill(filtered).reduce(function(acc, cur) { return acc.concat(cur) });
			},
			duration: function duration() {
			    return (this.filteredData.length * (this.speed / 1000));
			},
		}
	});
});
";
$document->addScriptDeclaration( $script );

?>
<div class="carousel_wrapper" id="app-<?php echo $uid ?>">
    <div class="carousel__scrollarea">
        <div v-on:mousemove="moveBox"
             class="carousel"
             ref="carousel"
             v-bind:class="{
                'carousel--stopped': hovered,
                'js-initialized': initialized
             }"
             v-bind:style="{
                width: width + 'px',
                animationDuration: duration + 's',
                '--animationLeft': (width / -2) + 'px'
             }"
        >
            <a class="carousel__ad"
               v-for="(product, index) in filteredData"
               class="ad__image"
               v-bind:key="product.id"
               v-on:mouseover="hover(true, product)" v-on:mouseleave="hover(false, product)"
               v-bind:class="{'ad__image--empty': product.images.length === 0}"
               v-bind:href="product.link"
               v-bind:style="{ backgroundImage: 'url(\'' + ((product.images[0]) ? product.images[0].href + '?width=250&quality=90' : '') + '\')' }">
            </a>
        </div>
    </div>
    <div v-if="hovered && showProduct" ref="box" class="carousel_box"
         v-bind:style="{left: boxPosition.x + 'px', top: boxPosition.y + 'px'}"
    >
        <h3><span v-if="showProduct.manufacturer">{{showProduct.manufacturer.value}}</span> <span v-if="showProduct.model">{{showProduct.model}}</span></h3>
        <div class="carousel_box__price" v-if="showProduct.price.values && showProduct.price.values.netto">
          <div class="carousel_box__price--netto">
            <span v-if="showProduct.vat.separable">{{ "<?php echo JText::_( 'COM_PIXELCMS_NETTO_SPRINTF' ) ?>" | sprintf(formatPrice(showProduct.price.values.netto)) }}</span>
              <span v-else>{{ formatPrice(showProduct.price.values.netto) }}</span>
            </div>
            <div class="carousel_box__price--brutto" v-if="showProduct.vat.separable">
              <span>{{ "<?php echo JText::_( 'COM_PIXELCMS_BRUTTO_SPRINTF' ) ?>" | sprintf(formatPrice(showProduct.price.values.brutto)) }}</span>
            </div>
        </div>
        <div class="carousel_box__price carousel_box__price--ask" v-else><?php echo JText::_( 'COM_PIXELCMS_ASK_FOR_PRICE' ) ?></div>
        <div v-if="showProduct.year"><?php echo JText::_( 'COM_PIXELCMS_BUILD_YEAR' ) ?>: {{showProduct.year}}</div>
        <div v-if="showProduct.power"><?php echo JText::_( 'COM_PIXELCMS_POWER' ) ?>: {{showProduct.power.show}}</div>
        <div v-if="showProduct.workhours"><?php echo JText::_( 'COM_PIXELCMS_WORKHOURS' ) ?>: {{showProduct.workhours.show}}</div>
    </div>
    <?php if ($model === 'tracktorpool_products' ): ?>
      <div class="traktorpool-copyright">
          <div>
              Ein Service von <a target="_blank" href="<?php echo "https://www.traktorpool.de/{$this->params->get('tracktorpool_alias')}/" ?>"><img src="https://www.traktorpool.de/images/frontend/de/logo.svg" alt="Traktorpool"></a>
          </div>
      </div>
    <?php endif; ?>
</div>
