<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 class="loyalty-suite-my-challenges">
          <div class="loyalty-suite-my-challenges__breadcrumbs">
            {{ $t('myChallenges') }}
          </div>
          <div class="loyalty-suite-my-challenges__list">
            <Challenge
              v-for="(challenge, index) in challenges"
              :key="challenge.id || index"
              :challenge="challenge"
              :myChallenges="true"
              :style="cardStyle"
              @share="openShare"
            />
            <div v-if="!challenges.length" class="loyalty-suite-my-challenges__empty">
              {{ $t('noMyChallenges') }}
            </div>
          </div>
          <span v-if="!isLastPage" @click="loadMore"
            :class="['loyalty-suite-button', { 'loyalty-suite-button_loading': isLoadingMore }]">
            {{ $t('loadMore') }}
          </span>
        </div>
        <ShareModal v-model="shareStatus" :link="currentLink" @close="closeShare" :copyLink="true" />
      </template>
    </template>
  </div>
</template>

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

export default defineComponent({
  components: { Challenge, ShareModal },
  setup() {
    const loading = ref(true);
    const error = ref<string | null>(null);
    const apiRoutes = window.loyalty_suite_account_data.apiRoutes;
    const nonce = window.loyalty_suite_account_data.nonce;
    const { t } = useI18n();
    const page = ref(1);
    const isLastPage = ref(true);
    const cardStyle = ref('classic');
    const isLoadingMore = ref(false);
    const challenges = ref([]);
    const shareStatus = ref(false);
    const currentLink = ref('');

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

    const loadMore = () => {
      page.value += 1;
      isLoadingMore.value = true;
      fetchData(page.value);
    };

    const closeShare = () => {
      shareStatus.value = false;
    }

    const openShare = (link: string) => {
      currentLink.value = link;
      shareStatus.value = true;
    };

    const fetchData = async (page = 1) => {
      try {
        const url = new URL(apiRoutes.account.my_challenges);
        url.searchParams.set('per_page', '12');
        url.searchParams.set('page', String(page));

        const response = await fetch(url.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();
        isLastPage.value = data.is_last_page;
        cardStyle.value = data.card_style;
        challenges.value.push(...data.posts);
      } catch (err: any) {
        error.value = err.message === '401' ? '401' : err.message || t('couldNotFetchData');
        console.error('API Error:', error.value);
      } finally {
        loading.value = false;
        isLoadingMore.value = false;
      }
    };

    onBeforeMount(fetchData);

    return {
      loading,
      error,
      errorMessage,
      challenges,
      isLastPage,
      isLoadingMore,
      loadMore,
      cardStyle,
      closeShare,
      openShare,
      shareStatus,
      currentLink
    };
  },
});
</script>

<style lang="scss" scoped>
.loyalty-suite-my-challenges {
  display: flex;
  width: 100%;
  flex-direction: column;

  &__breadcrumbs {
    display: flex;
    width: 100%;
    font-weight: 700;
    margin-top: 5px;
    margin-bottom: 20px;
    color: var(--loyalty-suite-primary);
  }

  &__header {
    display: flex;
    width: 100%;
    white-space: nowrap;
    align-items: center;
    margin-bottom: 10px;
  }

  &__list {
    width: calc(100% + 20px);
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
    margin: 0 -10px;
  }

  &__empty {
    display: flex;
    padding: 0 10px;
  }

  .loyalty-suite-button {
    align-self: center;
    margin-top: 15px;
  }
}
</style>
