<%
const stamps = _.cms('stamps') || {}
let stampsList
if (stamps && Array.isArray(stamps.stamps_list) && stamps.stamps_list.length) {
  stampsList = stamps.stamps_list
}
%>

<div id="product-block" class="product-block my-4 mb-lg-5">
  <div class="container">
    <section
      id="product"
      class="product"
      data-to-render="true"
      data-product-id="<%= _.state._id %>"
      data-sku="<%= _.state.sku %>"
    >
      <div id="product-dock">
        <!--
          `TheProduct` should be rendered (hydrated) here:
          https://developers.e-com.plus/storefront/@ecomplus/storefront-components/docs/TheProduct.html
        -->
      </div>

      <div class="row">
        <div class="col-12 col-md-6 mb-4">
          <!-- Picture(s) gallery will be inserted dynamically within `TheProduct` -->
          <% if (_.state.pictures) { %>
            <% const imgObj = _.ecomUtils.img(_.state, null, 'big') %>
            <% if (imgObj) { %>
              <% const [width, height] = (imgObj.size || '').split('x').map(px => parseInt(px, 10)) %>
              <div id="product-gallery">
                <div data-slot="stamps">
                  <% if (Array.isArray(stampsList) && stampsList.length) { %>
                    <div class="product__stamps">
                      <% for (stamp of stampsList) { 
                        if (stamp.img && (!stamp.skus || !stamp.skus.length || stamp.skus.includes(_.state.sku))) {
                          %>
                          <span class="product__stamps-<%= stamp.id && stamp.id.toLowerCase().replace(/\s/g, '-') %>">
                            <img src="<%= stamp.img %>" alt="<%= stamp.id %>">
                          </span>
                        <% } %>
                      <% } %>
                    </div>
                  <% } %>
                </div>
                <div
                  class="product__picture"
                  <% if (width) { %>
                    style="max-width: <%= width %>px"
                  <% } %>  
                >
                  <picture
                    <% if (width && height) { %>
                      class="picture"
                      style="--aspect-ratio-pc: <%= Math.round(height * 100 * 10000 / width) / 10000 %>%"
                    <% } %>
                  >
                    <source
                      srcset="<%= _.ecomUtils.img(_.state).url %>"
                      type="image/webp"
                      media="(max-width: 399.98px)"
                    >
                    <source
                      srcset="<%= imgObj.url %>"
                      type="image/webp"
                      media="(min-width: 400px)"
                    >
                    <img
                      src="<%= imgObj.url.replace(/\.webp$/, '') %>"
                      alt="<%= imgObj.alt || _.state.name %>"
                      <% if (imgObj.url.startsWith('https://ecoms1.com/')) { %>
                        crossorigin="anonymous"
                      <% } %>
                      <% if (height) { %>
                        width="<%= width %>"
                        height="<%= height %>"
                      <% } %>
                    >
                  </picture>
                </div>
              </div>
            <% } %>
          <% } %>
          <!-- Custom additional code on bottom of images gallery -->
        </div>

        <div class="col">
          <h1 class="product__name">
            <%= _.ecomUtils.name(_.state) %>
          </h1>
          <p class="product__sku">
            COD: <%= _.state.sku %>
          </p>

          <div id="product-actions">
            <div id="product-loading">
              <% if (_.state.available && _.state.visible && _.ecomUtils.inStock(_.state)) { %>
                <div class="product__price prices prices--big">
                  <strong class="prices__value">
                    <%= _.ecomUtils.formatMoney(_.ecomUtils.price(_.state)) %>
                  </strong>
                </div>
              <% } %>

              <% if (_.state.variations && _.state.variations.length) { %>
                <div data-slot="variations-info">
                  <!-- Custom info for products with variations, such as sizes table link -->
                  <% if (opt.size_guide && opt.size_guide.image) { %>
                    <% const sizeGuideTitle = opt.size_guide.title || _.dictionary('sizeGuide') %>
                    <div class="mb-3">
                      <a 
                        href="javascript:;"
                        data-toggle="modal"
                        data-target="#modal-size-guide"
                      >
                        <i class="i-ruler mr-1"></i> <%= sizeGuideTitle %>
                      </a>
                    </div>
                    <div 
                      class="modal modal-center fade" 
                      id="modal-size-guide" 
                      tabindex="-1" 
                      style="display: none;" 
                      aria-hidden="true"
                    >
                      <div class="modal-dialog">
                        <div class="modal-content">
                          <div class="modal-header d-flex align-items-center justify-content-between">
                            <h5 class="modal-title">
                              <%= sizeGuideTitle %>
                            </h5>
                            <button type="button" class="close" data-dismiss="modal">
                              <span aria-hidden="true">&times;</span>
                            </button>
                          </div>
                          <div class="modal-body">
                            <img 
                              class="img-fluid" 
                              src="<%= opt.size_guide.image %>" 
                              alt="<%= sizeGuideTitle %>"
                            >
                          </div>
                        </div>
                      </div>
                    </div>
                  <% } %>
                </div>
              <% } %>

              <div class="spinner-border m-4" role="status">
                <span class="sr-only">Loading...</span>
              </div>

              <div class="product__buy">
                <button
                  type="button"
                  class="btn btn-lg btn-primary"
                  onclick="ecomCart.addProduct(storefront.context.body)"
                  <% if (_.state.variations && _.state.variations.length) { %>
                    disabled
                  <% } %>
                >
                  <div data-slot="buy-button-content">
                    <i class="i-shopping-bag mr-1"></i>
                    <% if (_.state.kit_composition && _.state.kit_composition.length) { %>
                      <%= _.dictionary('buyKit') %>
                    <% } else { %> 
                      <% let buyText %>
                      <% if (Array.isArray(_.widgets)) { %>
                        <% const productWidget = _.widgets.find(item => item.pkg === '@ecomplus/widget-product') %>
                        <% buyText = productWidget && productWidget.options.buyText %>
                      <% } %>
                      <%= buyText || _.dictionary('buy') %>
                    <% } %>
                  </div>
                </button>
              </div>
            </div>
          </div>

          <% if (_.state.short_description) { %>
            <p class="product__info mt-3 lead">
              <%= _.state.short_description %>
            </p>
          <% } %>
        </div>
      </div>

      <%- await include('@/helpers/widgets-append', {
        _, opt: {}, field: 'productSlots'
      }) %>
    </section>

    <%- await include('@/helpers/widgets-append', {
      _, opt: {}, field: 'productBlockAppend'
    }) %>
  </div>
</div>

<%
const productJsonLd = {
  '@context': 'http://schema.org',
  '@type': 'Product',
  sku: _.state.sku,
  description: _.state.short_description || _.state.meta_description || _.ecomUtils.name(_.state),
  name: _.ecomUtils.name(_.state),
  offers: {
    '@type': 'Offer',
    url: `https://${_.settings.domain}/${_.state.slug}`,
    availability: `${(_.ecomUtils.inStock(_.state) ? 'In' : 'OutOf')}Stock`,
    priceCurrency: _.settings.currency,
    price: _.ecomUtils.price(_.state),
    itemCondition: `http://schema.org/${(_.state.condition === 'new' ? 'New' : 'Used')}Condition`,
    priceValidUntil: _.ecomUtils.onPromotion(_.state) && _.state.price_effective_date && _.state.price_effective_date.end
      ? _.state.price_effective_date.end.slice(0, 10)
      : undefined,
    seller: {
      '@type': 'Organization',
      name: _.settings.name || _.store.name
    }
  }
}
if (_.state.brands && _.state.brands[0]) {
  productJsonLd.brand = {
    '@type': 'Brand',
    name: _.state.brands[0].name
  }
}
if (_.state.pictures && _.state.pictures.length) {
  productJsonLd.image = _.ecomUtils.img(_.state, null, 'zoom').url
    .replace(/(\w+\.)?(ecoms\d)\.com/i, '$2-nyc3.nyc3.cdn.digitaloceanspaces.com')
}
if (_.state.mpn && _.state.mpn[0]) {
  productJsonLd.mpn = _.state.mpn[0]
}
if (_.state.gtin && _.state.gtin[0]) {
  productJsonLd.gtin = _.state.gtin[0]
}
%>
<script id="product-block-jsonld" type="application/ld+json"><%-
  JSON.stringify(productJsonLd)
%></script>
<script type="text/javascript">
  setTimeout(() => {
    const urlParams = new URLSearchParams(window.location.search);
    const variationId = urlParams.get('variation_id');
    const variations = window._context.body && window._context.body.variations;
    if (Array.isArray(variations) && variationId) {
      const selectedVariation = variations.find(variation => variation._id === variationId);
      if (selectedVariation) {
        const $jsonLd = document.querySelector('#product-block-jsonld');
        const jsonLd = JSON.parse($jsonLd.innerText);
        jsonLd.sku = selectedVariation.sku;
        jsonLd.offers.price = selectedVariation.price;
        jsonLd.name = (selectedVariation.name && selectedVariation.name.replace('"', '')) || jsonLd.name;
        jsonLd.offers.url = `${jsonLd.offers.url}?variation_id=${variationId}`;
        document.querySelector('#product-block-jsonld').innerText = JSON.stringify(jsonLd);
      }
    }
  }, 50);
</script>
