<template>
  <transition mode="out-in">
    <UiPopup
      v-if="model"
      v-model="model"
      :back="back"
      class="share-main"
      sheet
      @back="emit('back')"
    >
      <template #title>{{ $t('share') }}</template>
      <template
        v-if="$slots.card"
        #fixedContent
      >
        <div class="share-main__card">
          <slot name="card"/>
        </div>
      </template>
      <div class="share-main__popup-wrapper">
        <div class="share-main__buttons">
          <a
            v-for="(item, index) in buttons"
            :key="`share-button-${index}`"
            :href="item.link"
            class="share-main__button"
            target="_blank"
          >
            <img
              :alt="item.text"
              :src="`/icons/socials/${item.img}`"
              class="share-main__button-icon"
              width="28"
              height="28"
            >
          </a>
        </div>
        <div class="share-main__copy">
          <span class="share-main__copy-url">{{ fullUrl }}</span>
          <button
            :title="$t('copy')"
            class="share-main__copy-button"
            type="button"
            @click="copyUrl"
          >
            <UiIcon
              :class="{'--accent': isCopied}"
              :name="copyIcon"
              class="share-main__copy-icon"
              size="20"
            />
          </button>
        </div>
      </div>
    </UiPopup>
  </transition>
</template>

<script setup lang="ts">
const props = defineProps<{
  modelValue?: boolean
  url?: string
  back?: boolean
}>();

const emit = defineEmits<{
  (e: 'update:modelValue', value: boolean): void
  (e: 'back'): void
}>();

const model = computed({
  get: () => props.modelValue,
  set: (val: boolean) => emit('update:modelValue', val),
});

const route = useRoute();

const isCopied = ref(false);
let copyTimeout: ReturnType<typeof setTimeout> | null = null;

const origin = computed(() => import.meta.client ? window.location.origin : '');

const fullUrl = computed(() =>
    props.url ? origin.value + props.url : origin.value + route.fullPath
);

const isMobile = useState<boolean>('isMobile');

function canNativeShare() {
  return typeof navigator !== 'undefined' && !!navigator.share && isMobile.value;
}

function nativeShare() {
  navigator.share({
    title: document.title,
    text: document.title,
    url: fullUrl.value,
  }).catch((err) => {
    console.warn('Share failed:', err);
  });
}

watch(() => props.modelValue, (val) => {
  if (val && canNativeShare()) {
    emit('update:modelValue', false);
    nativeShare();
  }
});

function copyUrl() {
  if (!import.meta.client) return;
  navigator.clipboard.writeText(fullUrl.value).then(() => {
    isCopied.value = true;
  });
}

const copyIcon = computed(() => isCopied.value ? 'check' : 'copy');

watch(() => isCopied.value, (value) => {
  if (value) {
    copyTimeout = setTimeout(() => isCopied.value = false, 3000);
  }
});

onBeforeUnmount(() => {
  if (copyTimeout) clearTimeout(copyTimeout);
});

const buttons = computed(() => {
  return [
    {
      img: 'telegram.svg',
      link: `https://t.me/share/url?url=${encodeURIComponent(fullUrl.value)}`,
      text: 'Telegram',
    },
    {
      img: 'whatsapp.svg',
      link: `https://wa.me/?text=${encodeURIComponent(fullUrl.value)}`,
      text: 'Whatsapp',
    },
    {
      img: 'x.svg',
      link: `https://x.com/intent/tweet?url=${encodeURIComponent(fullUrl.value)}`,
      text: 'X',
    },
  ];
});
</script>

<style lang="scss">
.share-main .ui-popup__back {
  @include from-br(sm) {
    display: none;
  }
}

.share-main__popup-wrapper {
  display: grid;
  margin: 0 auto;
  margin-bottom: 12px;

  @include from-br(sm) {
    width: 414px;
  }

  @include to-br(sm) {
    padding: 20px;
    padding-bottom: 48px;
  }
}

.share-main__wrapper {
  @include to-br(sm) {
    padding: 16px;
  }
}

.share-main__buttons {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  column-gap: 32px;
  margin: 0 auto;
  padding-top: 4px;
  padding-bottom: 24px;

  @include from-br(sm) {
    column-gap: 16px;
    padding-bottom: 16px;
  }
}

.share-main__button {
  --size: 56px;

  display: grid;
  place-content: center;
  width: var(--size);
  height: var(--size);
  border-radius: $radius-full;

  @include from-br(sm) {
    --size: 44px;
  }

  @include hover(opacity) {
    opacity: 0.9;
  }
}

.share-main__cancel-wrapper {
  margin-top: 16px;
  padding-top: 16px;
  border-top: 1px solid $share-cancel-border;

  @include from-br(sm) {
    margin-top: 12px;
    padding-top: 12px;
  }
}

.share-main__button:first-child {
  background-color: #2aabee;
}

.share-main__button:nth-child(2) {
  background-color: #25d366;
}

.share-main__button:last-child {
  background-color: $share-button-copy-bg;
}

.share-main__button-icon {
  filter: brightness(0) invert(1);

  @include from-br(sm) {
    $size: 20px;

    width: $size;
    height: $size;
  }
}

.share-main__copy {
  display: grid;
  column-gap: 8px;
  place-items: center start;
  padding: 16px;
  grid-template-columns: 1fr auto;
  background-color: $share-copy-bg;
  border-radius: $radius-xl;
  border: 1px solid $share-copy-border;

  @include from-br(sm) {
    padding: 8px 16px;
  }
}

.share-main__copy-url {
  @include font-sm;

  grid-column: 1;
  color: $share-copy-url-text;
  max-width: 100%;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.share-main__copy-button {
  grid-column: 2;
  display: grid;
  place-content: center;
  color: $share-copy-button;

  @include from-br(sm) {
    padding: 8px;
    color: $share-copy-button-desktop;
  }

  @include hover(color) {
    color: $share-copy-button--hover;
  }
}

.share-main__copy-icon.--accent {
  color: $share-copy-accent;
}
</style>
