<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-profile">
          <div v-if="userData.wallets.length" class="loyalty-suite-profile__card">
            <div class="loyalty-suite-profile__card-wrapper">
              <WalletsBlock :wallets="userData.wallets" :currency="currency" />
            </div>
          </div>
          <div v-if="showSectionsData.rewards" class="loyalty-suite-profile__card">
            <div class="loyalty-suite-profile__card-wrapper">
              <RewardsBlock :rewards="userData.rewards" />
            </div>
          </div>
          <div v-if="showSectionsData.ranks" class="loyalty-suite-profile__card">
            <div class="loyalty-suite-profile__card-wrapper">
              <RanksBlock :ranks="userData.ranks" :style="cardStyles['rank']" @share="openShare" />
            </div>
          </div>
          <div v-if="showSectionsData.achievements" class="loyalty-suite-profile__card">
            <div class="loyalty-suite-profile__card-wrapper">
              <AchievementsBlock :achievements="userData.achievements" :style="cardStyles['achievement']" @share="openShare" />
            </div>
          </div>
          <div v-if="showSectionsData.challenges" class="loyalty-suite-profile__card">
            <div class="loyalty-suite-profile__card-wrapper">
              <ChallengesBlock :challenges="userData.challenges" :style="cardStyles['challenge']" @share="openShare" />
            </div>
          </div>
        </div>
        <ShareModal v-model="shareStatus" :link="currentLink" @close="closeShare" :copyLink="true" />
      </template>
    </template>
  </div>
</template>

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

export default defineComponent({
  components: { RanksBlock, WalletsBlock, AchievementsBlock, ChallengesBlock, RewardsBlock, 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 currency = ref({ symbol: '$' });
    const shareStatus = ref(false);
    const currentLink = ref('');
    const errorMessage = computed(() => {
      if (error.value === '401') {
        return;
      }
      return error.value;
    });

    const userData = ref({
      achievements: [],
      challenges: [],
      ranks: [],
      wallets: [],
      rewards: []
    });

    const cardStyles = ref({
      'achievement': 'classic',
      'challenge': 'classic',
    });

    const showSectionsData = ref({
      ranks: true,
      achievements: true,
      challenges: true,
      rewards: true,
    });

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

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

    const fetchCurrency = async () => {
      try {
        const response = await fetch(apiRoutes.account.currency, {
          method: 'GET',
          headers: {
            'X-WP-Nonce': nonce,
            'Content-Type': 'application/json',
          }
        });

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

        const data = await response.json();
        currency.value = data;
      } catch (err: any) {
        error.value = err.message === '401'
          ? '401'
          : err.message || t('couldNotFetchData');
        console.error('API Error:', error.value);
      }
    };

    const fetchData = async () => {
      try {
        const response = await fetch(apiRoutes.account.profile, {
          method: 'GET',
          headers: {
            'X-WP-Nonce': nonce,
            'Content-Type': 'application/json',
          },
        });

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

        const data = await response.json();

        userData.value.ranks = data.ranks;
        userData.value.wallets = data.wallets;
        userData.value.achievements = data.achievements.posts;
        userData.value.challenges = data.challenges.posts;
        userData.value.rewards = data.rewards.posts;
        cardStyles.value = data.card_styles;
        showSectionsData.value = data.sections;
      } catch (err: any) {
        error.value = err.message === '401'
          ? '401'
          : err.message || t('couldNotFetchData');
        console.error('API Error:', error.value);
      }
    };

    onBeforeMount(async () => {
      try {
        await Promise.all([fetchData(), fetchCurrency()]);
      } catch (err) {
        console.error('Api error:', err);
      } finally {
        loading.value = false;
      }
    });

    return {
      loading,
      error,
      errorMessage,
      userData,
      currency,
      showSectionsData,
      cardStyles,
      closeShare,
      openShare,
      shareStatus,
      currentLink
    };
  },
});
</script>

<style lang="scss" scoped>
.loyalty-suite-profile {
  width: calc(100% + 20px);
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(320px, 1fr));
  margin: 0 -10px;

  &__card {
    display: flex;
    min-height: 323px;
    padding: 10px;

    &-wrapper {
      display: flex;
      width: 100%;
      height: 100%;
      padding: 10px;
      border-radius: 8px;
      background: var(--loyalty-suite-light);
      border: 1px solid var(--loyalty-suite-borders-60);
    }
  }
}

@media (max-width: 576px) {
  .loyalty-suite-profile {
    &__card {
      width: 100%;
      max-width: 100%;
    }

    &__wallets {
      width: 100%;
    }
  }
}
</style>
