<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-ranks-page">
          <div v-for="(rankSet, index) in rankSets" class="loyalty-suite-ranks-page__rankset">
            <RankSet :rankSet="rankSet" :index="index" :style="cardStyle" />
          </div>
          <div v-if="!rankSets.length" class="loyalty-suite-ranks-page__empty">
            {{ $t('noRanks') }}
          </div>
        </div>
      </template>
    </template>
  </div>
</template>

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

export default defineComponent({
  components: { RankSet },
  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 rankSets = ref([]);
    const cardStyle = ref('classic');

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

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

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

        const data = await response.json();
        rankSets.value = data.rank_sets;
        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, rankSets, cardStyle };
  },
});
</script>

<style lang="scss" scoped>
.loyalty-suite-ranks-page {
  display: flex;
  flex-wrap: wrap;
  width: calc(100% + 30px);
  margin: 0 -20px;

  &__rankset {
    display: flex;
    width: 100%;
    padding: 10px;
  }

  &__empty {
    display: flex;
    padding: 10px 20px;
  }
}
</style>
