<template>
  <teleport to="body">
    <transition name="loyalty-suite-fade">
      <div v-if="isOpen" class="loyalty-suite-share-modal-wrapper" @click.self="close">
        <div class="loyalty-suite-share-modal">
          <div class="loyalty-suite-share-modal__title">
            {{ $t('shareLink') }}
          </div>

          <div class="loyalty-suite-share-modal__content">
            <div
              v-for="network in shareNetworks"
              :key="network.key"
              class="loyalty-suite-share-modal__block"
            >
              <a
                :href="network.url ? network.url(link) : link"
                class="loyalty-suite-share-modal__link"
                target="_blank"
                rel="noopener"
                @click="onClickNetwork(network, $event)"
              >
                <img :src="`${iconsUrl}${network.key}.png`">
                <span v-if="network.key === 'copyLink'">
                  {{ copied ? $t('copied') : $t('copyLink') }}
                </span>
                <span v-else>
                  {{ $t(network.key) }}
                </span>
              </a>
            </div>
          </div>

          <div class="loyalty-suite-share-modal__actions">
            <span class="loyalty-suite-button" @click="close">
              {{ $t('close') }}
            </span>
          </div>
        </div>
      </div>
    </transition>
  </teleport>
</template>

<script lang="ts">
import { defineComponent, onUnmounted, watch, computed, ref } from 'vue';

export default defineComponent({
  props: {
    modelValue: {
      type: Boolean,
      required: true,
    },
    link: {
      type: String,
      required: true,
    },
    copyLink: {
      type: Boolean,
      default: false,
    }
  },
  emits: ['update:modelValue', 'close'],
  setup(props, { emit }) {
    const isOpen = computed({
      get: () => props.modelValue,
      set: (val: boolean) => emit('update:modelValue', val),
    });

    const close = () => {
      emit('update:modelValue', false);
      emit('close');
    };

    watch(isOpen, (val) => {
      if (val) {
        document.body.classList.add('loyalty-suite-no-scroll');
      } else {
        document.body.classList.remove('loyalty-suite-no-scroll');
      }
    });

    onUnmounted(() => {
      document.body.classList.remove('loyalty-suite-no-scroll');
    });

    const iconsUrl = window.loyalty_suite_account_data.iconsUrl;

    const baseNetworks = [
      {
        key: 'telegram',
        url: (link: string) => `https://t.me/share/url?url=${encodeURIComponent(link)}`
      },
      {
        key: 'whatsapp',
        url: (link: string) => `https://wa.me/?text=${encodeURIComponent(link)}`
      },
      {
        key: 'facebook',
        url: (link: string) => `https://www.facebook.com/sharer/sharer.php?u=${encodeURIComponent(link)}`
      },
      {
        key: 'twitter',
        url: (link: string) => `https://twitter.com/intent/tweet?url=${encodeURIComponent(link)}`
      },
      {
        key: 'reddit',
        url: (link: string) => `https://www.reddit.com/submit?url=${encodeURIComponent(link)}`
      },
      {
        key: 'linkedin',
        url: (link: string) => `https://www.linkedin.com/sharing/share-offsite/?url=${encodeURIComponent(link)}`
      },
      {
        key: 'pinterest',
        url: (link: string) => `https://pinterest.com/pin/create/button/?url=${encodeURIComponent(link)}`
      },
      {
        key: 'vk',
        url: (link: string) => `https://vk.com/share.php?url=${encodeURIComponent(link)}`
      },
      {
        key: 'threads',
        url: (link: string) => `https://www.threads.net/intent/post?url=${encodeURIComponent(link)}`
      },
      {
        key: 'email',
        url: (link: string) =>
          `mailto:?subject=${encodeURIComponent('Check this out')}&body=${encodeURIComponent(link)}`
      },
    ];

    const shareNetworks = computed(() => {
      const list = [...baseNetworks];
      if (props.copyLink) {
        list.push({
          key: 'copyLink',
          url: (link: string) => link,
        });
      }
      return list;
    });

    const copied = ref(false);
    let copiedTimeout: number | undefined;

    const copyToClipboard = async () => {
      try {
        if ('clipboard' in navigator && navigator.clipboard?.writeText) {
          await navigator.clipboard.writeText(props.link);
        } else {
          const textarea = document.createElement('textarea');
          textarea.value = props.link;
          textarea.style.position = 'fixed';
          textarea.style.left = '-9999px';
          document.body.appendChild(textarea);
          textarea.select();
          document.execCommand('copy');
          document.body.removeChild(textarea);
        }

        copied.value = true;

        if (copiedTimeout) {
          window.clearTimeout(copiedTimeout);
        }

        copiedTimeout = window.setTimeout(() => {
          copied.value = false;
        }, 2000);
      } catch (e) {
        console.error('Copy failed', e);
      }
    };

    const onClickNetwork = (network: { key: string }, event: MouseEvent) => {
      if (network.key === 'copyLink') {
        event.preventDefault();
        copyToClipboard();
      }
    };

    return {
      isOpen,
      close,
      shareNetworks,
      iconsUrl,
      copied,
      onClickNetwork,
    };
  }
});
</script>

<style lang="scss" scoped>
.loyalty-suite-share-modal {
  display: flex;
  flex-direction: column;
  overflow-y: auto;
  padding: 20px;
  min-width: 350px;
  max-width: 600px;
  max-height: calc(100vh - 48px);
  border-radius: 8px;
  background: var(--loyalty-suite-light);
  box-shadow: 0 5px 15px 0 var(--loyalty-suite-borders-40);

  &-wrapper {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: rgba(0, 0, 0, 0.4);
    z-index: 2000;
    display: flex;
    align-items: center;
    justify-content: center;
  }

  &__title {
    display: flex;
    width: 100%;
    margin-bottom: 15px;
    color: var(--loyalty-suite-primary);
  }

  &__content {
    display: flex;
    flex-wrap: wrap;
    width: calc(100% + 30px);
    margin: 0 -15px;
  }

  &__block {
    display: flex;
    width: 25%;
    padding: 15px;
  }

  a.loyalty-suite-share-modal__link {
    display: flex;
    width: auto;
    align-items: center;
    text-decoration: none;
    font-size: 14px;
    color: var(--loyalty-suite-dark);
    line-height: normal;
    font-weight: 400;
    white-space: nowrap;
    transition: 0.3s;

    img {
      display: flex;
      width: 36px;
      height: 36px;
      margin-right: 7px;
    }

    &:focus {
      box-shadow: none;
      outline: none;
      border: none;
    }

    &:hover {
      box-shadow: none;
      outline: none;
      border: none;
      color: var(--loyalty-suite-primary);
    }
  }

  &__actions {
    margin-top: 20px;
    display: flex;
    justify-content: center;
  }
}

@media (max-width: 620px) {
  .loyalty-suite-share-modal {
    width: 100%;
    height: 100%;
    max-height: 100vh;
    border-radius: 0;

    &__block {
      width: 50%;
    }
  }
}
</style>
