<template>
  <div class="loyalty-suite-wrapper">
    <div class="loyalty-suite-loading" v-if="loading">
      <div class="loyalty-suite-spinner"></div>
    </div>

    <template v-else>
      <div v-if="errorMessage" class="loyalty-suite-api-error-message">
        <span>{{ errorMessage }}</span>
      </div>
      <template v-if="!error">
        <div v-if="hasItem" class="loyalty-suite-share">
          <div class="loyalty-suite-share__wrapper">
            <div class="loyalty-suite-share__user">
              {{ displayName }}
            </div>
            <div class="loyalty-suite-share__label">
              {{ itemTypeLabel }}
            </div>

            <!-- Achievement -->
            <Achievement
              v-if="isAchievement"
              :achievement="shareData?.item"
              :style="cardStyle"
            />

            <!-- Challenge -->
            <Challenge
              v-else-if="isChallenge"
              :challenge="shareData?.item"
              :style="cardStyle"
            />

            <!-- Rank -->
            <Rank
              v-else-if="isRank"
              :rank="shareData?.item"
              :style="cardStyle"
            />

          </div>
        </div>
      </template>
    </template>
  </div>
</template>

<script lang="ts">
import { defineComponent, ref, computed, onBeforeMount } from 'vue';
import { useRoute } from 'vue-router';
import { useI18n } from 'vue-i18n';
import Challenge from '../components/Challenge.vue';
import Achievement from '../components/Achievement.vue';
import Rank from '../components/Rank.vue';

export default defineComponent({
  components: { Achievement, Challenge, Rank },
  setup() {
    const loading = ref(true);
    const error = ref<string | null>(null);
    const route = useRoute();
    const { t } = useI18n();
    const apiRoutes = window.loyalty_suite_account_data.apiRoutes;
    const nonce = window.loyalty_suite_account_data.nonce;
    const cardStyle = ref('classic');
    const shareData = ref<{ user: any; item: any } | null>(null);

    const userId = computed(() => (route.query.user ? String(route.query.user) : ''));
    const itemType = computed(() =>
      route.query.type ? String(route.query.type) : '',
    );
    const itemId = computed(() =>
      route.query.id ? String(route.query.id) : '',
    );

    const displayName = computed(() => {
      if (!shareData.value?.user) return '';
      const u = shareData.value.user;

      const full = [u.first_name, u.last_name].filter(Boolean).join(' ').trim();
      if (full) return full;

      if (u.nickname) return u.nickname;
      if (u.display_name) return u.display_name;
      if (userId.value) return `User #${userId.value}`;

      return 'User';
    });

    const itemTypeLabel = computed(() => {
      switch (itemType.value) {
        case 'challenge':
          return t('completedChallenge') + '!';
        case 'achievement':
          return t('achievementEarned') + '!';
        case 'rank':
          return t('rankEarned') + '!';
        default:
          return '';
      }
    })

    const hasItem = computed(() => !!shareData.value?.item);
    const isAchievement = computed(() => itemType.value === 'achievement');
    const isChallenge = computed(() => itemType.value === 'challenge');
    const isRank = computed(() => itemType.value === 'rank');

    const errorMessage = computed(() => {
      if (!error.value) {
        return null;
      }

      if (error.value === '401') {
        return null;
      }

      if (error.value === 'missing_params') {
        return t('shareMissingData');
      }

      return t('couldNotFetchData');
    });

    const fetchData = async () => {
      shareData.value = null;

      if (!userId.value || !itemType.value || !itemId.value) {
        error.value = 'missing_params';
        loading.value = false;
        return;
      }

      try {
        const params = new URLSearchParams({
          user: userId.value,
          type: itemType.value,
          id: itemId.value,
        });

        const url = new URL(apiRoutes.account.share);

        const response = await fetch(`${url}?${params.toString()}`, {
          method: 'GET',
          headers: {
            'X-WP-Nonce': nonce,
            'Content-Type': 'application/json',
          },
        });

        if (!response.ok) throw new Error(response.status);

        const data = await response.json();
        shareData.value = {
          user: data.user,
          item: data.item,
        };
        cardStyle.value = data.card_style;

      } catch (err: any) {
        error.value = err.message === '401' ? '401' : err.message || t('couldNotFetchData');
        console.error('API Error:', error.value);
      } finally {
        loading.value = false;
      }
    };

    onBeforeMount(fetchData);

    return { loading, error, errorMessage, displayName, itemTypeLabel, shareData, hasItem, cardStyle, isAchievement, isChallenge, isRank };
  },
});
</script>

<style lang="scss" scoped>
.loyalty-suite-share {
  display: flex;
  width: 400px;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  background: var(--loyalty-suite-light);
  padding: 30px;
  border-radius: 8px;
  border: 2px solid var(--loyalty-suite-primary);
  &__wrapper {
    display: flex;
    width: 100%;
    flex-direction: column;
    align-items: center;
    justify-content: center;
  }
  &__user {
    display: flex;
    width: 100%;
    font-size: 18px;
    font-weight: 700;
    text-align: center;
    margin-bottom: 10px;
    text-transform: uppercase;
    justify-content: center;
    color: var(--loyalty-suite-dark);
  }
  &__label {
    display: flex;
    width: 100%;
    font-size: 16px;
    font-weight: 700;
    text-align: center;
    margin-bottom: 30px;
    text-transform: uppercase;
    justify-content: center;
    color: var(--loyalty-suite-positive);
  }
  :deep(.loyalty-suite-challenge__card) {
    width: 300px;
  }
  :deep(.loyalty-suite-achievement__card) {
    width: 300px;
  }
  :deep(.loyalty-suite-rank__card) {
    width: 300px;
  }
}
</style>
