<template>
  <div class="productcard_container">
    <div class="row productcard_container-basic">
      <div class="image_container col-md-5">
        <img :src="getProductImg(product)" class="image" alt="" />
      </div>
      <div class="info_container col-md-5">
        <h2 variant="primary">
          {{ product?.name }}
        </h2>
        <span v-if="product?.price" class="price">{{
          `${product?.price}€`
        }}</span>
        <span v-else class="price">Precio a consultar</span>
        <span v-if="Number(product?.shipping_cost)"
          >| {{ `Gastos de envío ${product?.shipping_cost}€` }}</span
        >
        <span v-else>| Sin gastos de envío</span>

        <span v-if="product?.stock">| {{ `Stock ${product?.stock}€` }} </span>
        <p
          v-if="product?.description"
          class="description"
          v-html="sanitize(product?.description)"
        ></p>
        <span v-if="product?.shipping_terms">{{ product?.shipping_terms }}</span>
        <BCollapse visible accordion="my-accordion">
          <div class="tags_container">
            <NuxtLink
              v-for="n in product?.tags"
              :key="n"
              :to="tagRoute(n)"
              class="tag_container"
            >
              <img
                class="tag_img"
                alt="tag image"
                src="@/assets/img/latienda-tag.svg"
              />
              <span>{{ n }}</span>
            </NuxtLink>
          </div>
          <div class="smlogos_container">
            <p class="share-text">Comparte:</p>
            <div class="smlogo_container">
              <a @click="shareFacebook">
                <img
                  alt="facebook logo"
                  class="smlogo_img"
                  src="@/assets/img/latienda-smlogo-facebook.svg"
                />
              </a>
            </div>
            <a :href="shareTwitter()">
              <div class="smlogo_container">
                <img
                  alt="twitter logo"
                  class="smlogo_img"
                  src="@/assets/img/latienda-smlogo-twitter.svg"
                />
              </div>
            </a>
            <a
              :href="shareWhatsApp()"
              data-action="share/whatsapp/share"
              target="_blank"
              title="latiendacoop"
            >
              <div class="smlogo_container">
                <img
                  alt="whatsapp logo"
                  class="smlogo_img"
                  src="@/assets/img/latienda-smlogo-whatsapp.svg"
                />
              </div>
            </a>
          </div>
          <div class="coop_info">
            <NuxtLink :to="`/c/${company?.id}`">
              <h2>{{ company?.company_name }}</h2>
            </NuxtLink>
            <p class="description">{{ company?.description }}</p>
            <a href="#">{{ company?.web_link }}</a>
          </div>
        </BCollapse>
      </div>
      <div class="col-md-2 button_container-detail" align="center">
        <button class="button_buy-simple" @click="buyIntent">
          <img
            class="button_cart_img"
            alt="cart"
            src="@/assets/img/latienda-carrito.svg"
          />
        </button>
        <div
          v-if="product?.discount && product?.discount > 0"
          class="discount-tag"
        >
          {{ `Descuento ${product?.discount}%` }}
        </div>
      </div>
    </div>
    <div class="related_products">
      <h2 v-if="related">Productos relacionados</h2>
      <h2 v-else>Otros productos</h2>
      <ProductsRelated :related-products="relatedProducts" />
    </div>
    <ProductModal v-if="modal" :product="product" @close-modal="closeModal" />
  </div>
</template>

<script>
import { mapState } from 'pinia'
import DOMPurify from 'dompurify'
import socialShare from '~/utils/socialShare'
export default {
  props: {
    product: {
      type: Object,
      default: () => ({}),
    },
    company: {
      type: Object,
      default: () => ({}),
    },
    relatedProducts: {
      type: Array,
      default: () => [],
    },
    related: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      modal: true,
      productUrl: null,
      geolocation: null,
    }
  },
  computed: {
    ...mapState(useAuthStore, ['id', 'access']),
  },
  mounted() {
    this.productUrl = window.location.href
    this.sendLog('view')
  },

  methods: {
    getProductImg(product) {
      if (product && product.image) 
        return product.image
      return `@/assets/img/latienda-product-default.svg`
    },
    tagRoute(tag) {
      return `/busqueda?tags=${tag}`
    },
    openUrl(url) {
      window.open(url)
    },
    closeModal(value) {
      this.modal = false
      if (value === 200) {
        this.$bvToast.toast(`Email enviado correctamente`, {
          title: 'latienda.coop',
          autoHideDelay: 5000,
          appendToast: true,
        })
      } else if (value) {
        this.$bvToast.toast(`Se ha producido un error en el envío`, {
          title: 'latienda.coop',
          autoHideDelay: 5000,
          appendToast: true,
          variant: 'danger',
        })
      }
    },
    // TODO: implement buyIntent (review functionality)
    buyIntent() {
      this.sendLog('shop')
      return this.product.url
        ? this.openUrl(this.product.url)
        : (this.modal = true)
    },

    async getPosition() {
      const geoLocation = () =>
        new Promise((resolve, reject) =>
          navigator.geolocation.getCurrentPosition(
            (posData) => {
              resolve(posData)
            },
            (error) => {
              reject(error)
            }
          )
        )
      try {
        const position = await geoLocation()
        const geo = {
          latitude: position.coords.latitude,
          longitude: position.coords.longitude,
        }
        return geo
      } catch {
        const geo = null
        return geo
      }
    },

    async sendLog(action) {
      const geo = await this.getPosition()
      try {
        const config = useRuntimeConfig()
        const accessToken = this.access
        const response = await $fetch('https://api.ipify.org?format=json', {
          baseURL: config.public.baseURL,
          method: 'GET'
        })
        const ip = response.ip
        const object = {
          action: action,
          action_object: {
            model: 'product',
            id: this.product.id,
          },
        }
        console.log('Sending log OBJECT:', object)
        if (ip) object.ip = ip
        if (geo) object.geo = geo
        //TODO: review problems with 406 error backend
        await $fetch(`/stats/me/`, {
          baseURL: config.public.baseURL,
          method: 'POST',
          body: object,
          headers: {
              Authorization: `Bearer ${accessToken}`
            }
        })
      } catch (error) {
        console.error('Error sending log:', error)
      }
    },

    shareFacebook() {
      const url = socialShare.facebook(this.productUrl)
      window.open(url, '_blank')
    },
    shareTwitter() {
      return socialShare.twitter(this.productUrl)
    },
    shareWhatsApp() {
      return socialShare.whatsApp(this.productUrl)
    },

    sanitize(dirtyHtml) {
      return DOMPurify.sanitize(dirtyHtml, {
        ALLOWED_TAGS: [
          'b',
          'i',
          'em',
          'strong',
          'a',
          'p',
          'br',
          'ul',
          'li',
          'ol',
          'span',
          'h1',
          'h2',
          'h3',
        ],
        ALLOWED_ATTR: ['href', 'target', 'rel', 'class'],
      })
    },
  },
}
</script>

<style lang="scss" scoped>
.productcard_container {
  border: 3px solid $color-grey-nav;
  border-radius: 5px;
  margin-bottom: 12px;
}
.productcard_container-basic {
  padding: 25px 20px;
}

.image_container {
  height: 100%;
  overflow: hidden;
  margin: auto;
}

.image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.info_container {
  h2 {
    outline: none;
    font-weight: medium;
    color: $color-navy;
    font-size: $m;
  }
  .price {
    font-weight: bold;
    color: $color-navy;
    font-size: $m;
  }
  span {
    color: $color-greytext;
  }
  .description {
    margin-top: 8px;
    font-family: $font-secondary;
    font-size: $s;
    color: $color-greytext;
  }
}

.button_container {
  display: flex;
  flex-direction: column;
  font-size: $m;

  span {
    margin-top: 15px;
    text-align: center;
    font-weight: medium;
    font-size: $m;
    color: $color-navy;
  }

  .button_buy {
    border: 3px solid $color-orange;
    border-radius: 5px;
    background-color: $color-light;

    &:hover {
      box-shadow: 0 4px 16px rgba(99, 99, 99, 0.2);
      transition: all 0.2s ease;
    }

    span {
      color: $color-orange;
      font-weight: $bold;
      display: inline-block;
      margin-bottom: 15px;
    }
  }
}

.button_buy-simple {
  border: 3px solid $color-orange;
  border-radius: 8px;
  background-color: $color-light;
  padding: 10px 20px;

  &:hover {
    box-shadow: 0 4px 16px rgba(99, 99, 99, 0.2);
    transition: all 0.2s ease;
  }

  .button_cart_img {
    margin-right: 0;
  }
}

.tag_container {
  margin: 25px 6px 0 0;
  border: 2px solid $color-greylayout;
  border-radius: 5px;
  padding: 6px 10px;
  display: inline-block;
  font-family: $font-secondary;
  font-size: $xs;
  color: $color-greytext;

  .tag_img {
    width: 18px;
  }
}

.share-text {
  color: $color-navy;
  font-size: $m;
  margin-top: 2rem;
  padding-bottom: 0.2em;
}

.smlogo_container {
  cursor: pointer;
  display: inline-block;
  margin-bottom: 0.5rem;

  .smlogo_img {
    cursor: pointer;
    width: 40px;
    fill: $color-greylayout;
  }
  img:hover {
    transform: scale(1.1);
    transition: all 0.2s ease;
  }
}

.button_cart_img {
  width: 20px;
  margin-right: 10px;
}

.coop_info {
  margin-top: 25px;
  p,
  a {
    margin-top: 8px;
    font-family: $font-secondary;
    font-size: $s;
    color: $color-greytext;
  }
  a {
    text-decoration: underline;
  }
}

.related_products {
  background-color: $color-lighter-green;
  text-align: center;
  padding: 0 15px;

  h2 {
    margin: 35px auto;
    font-weight: medium;
    color: $color-navy;
    font-size: $m;
    display: inline-block;
  }
}

.discount-tag {
  margin: 5px;
  border: none;
  background-color: $color-green;
  border-radius: 5px;
  padding: 6px 10px;
  display: inline-block;
  font-family: $font-secondary;
  font-size: $xs;
  color: $color-greytext;
}

.content > h2,
h3,
p {
  margin: 0;
}
</style>
