<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-achievement">
          <div class="loyalty-suite-achievement__breadcrumbs">
            {{ $t('achievement') }}
          </div>
          <div class="loyalty-suite-achievement__header">
            <img v-if="achievement.image_type === 'icon' && achievement.icon" :src="achievement.icon"
              class="loyalty-suite-achievement__icon">
            <img v-if="achievement.image_type === 'image' && achievement.image" :src="achievement.image"
              class="loyalty-suite-achievement__image">
            <div class="loyalty-suite-achievement__title">
              {{ achievement.name }}
            </div>
          </div>
          <div v-if="achievement.description.length" v-html="achievement.description"
            class="loyalty-suite-achievement__description"></div>
          <div v-if="achievement.progress > 0" class="loyalty-suite-achievement__progress">
            <div class="loyalty-suite-achievement__progress-title">
              {{ $t('achievementProgress') }}:
            </div>
            <div class="loyalty-suite-achievement__progress-wrapper">
              <div class="loyalty-suite-achievement__progress-bar" :style="{ width: achievement.progress + '%' }"></div>
            </div>
            <div class="loyalty-suite-achievement__progress-value">
              {{ achievement.progress }}% {{ $t('complete') }}
            </div>
          </div>
          <div class="loyalty-suite-achievement__tabs">
            <span v-for="tab in tabs" :key="tab.name" class="loyalty-suite-achievement__tabs-button"
              :class="{ 'loyalty-suite-achievement__tabs-button_active': activeTab === tab.name }"
              @click="activeTab = tab.name">
              {{ tab.label }}
            </span>
          </div>
          <div class="loyalty-suite-achievement__panels">
            <div v-if="activeTab === 'conditions'" class="loyalty-suite-achievement__panels-container">
              <div v-if="achievement.reward_sources.length" class="loyalty-suite-achievement__reward-sources">
                <div
                  v-for="(reward, idx) in achievement.reward_sources"
                  :key="idx"
                  class="loyalty-suite-achievement__reward-sources-item"
                >
                  <template v-if="reward.source === 'challenge'">
                    {{ $t('needChallengeComplete') }}:
                    <router-link
                      :to="`/challenge/${reward.challenge_id}`"
                      class="loyalty-suite-achievement__reward-sources-link"
                    >
                      {{ reward.challenge_name }}
                    </router-link>
                  </template>

                  <template v-else-if="reward.source === 'mission'">
                    {{ $t('needChallengeMissionComplete') }}:
                    <router-link
                      :to="`/challenge/${reward.challenge_id}`"
                      class="loyalty-suite-achievement__reward-sources-link"
                    >
                      {{ reward.challenge_name }}
                    </router-link>
                  </template>
                </div>
              </div>
              <Conditions :conditions="achievement.conditions" :order="achievement.condition_order"
                :currency="currency" :entityId="parseInt(route.params.id)" :entityType="'achievement'" />
            </div>
            <div v-if="activeTab === 'rewards'" class="loyalty-suite-achievement__panels-container">
              <div class="loyalty-suite-achievement__rewards">
                <Reward v-for="(reward, index) in achievement.rewards" :key="reward.id || index" :reward="reward"
                  :status="achievement.progress === 100 ? 'complete' : ''" />
              </div>
            </div>
          </div>
        </div>
      </template>
    </template>
  </div>
</template>

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

export default defineComponent({
  components: { Conditions, Reward },
  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 route = useRoute();
    const activeTab = ref('conditions');
    const tabs = ref<{ name: string; label: string }[]>([]);
    const currency = ref({ symbol: '$' });
    const achievement = ref([]);

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

    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 fetchAchievement = async () => {
      try {
        const buildApiUrl = (base, params = {}) => {
          const url = new URL(base, window.location.origin);
          Object.entries(params).forEach(([k, v]) => {
            if (v !== undefined && v !== null && v !== '') url.searchParams.set(k, v);
          });
          return url.toString();
        };

        const response = await fetch(
          buildApiUrl(apiRoutes.account.achievement, {
            id: Number(route.params.id),
          }),
          {
            method: 'GET',
            headers: {
              'X-WP-Nonce': nonce,
              'Content-Type': 'application/json',
            },
            credentials: 'same-origin',
          }
        );

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

        const data = await response.json();

        achievement.value = data.achievement;

        if (
          (achievement.value.conditions && achievement.value.conditions.length) ||
          (achievement.value.reward_sources && achievement.value.reward_sources.length)
        ) {
          const condCount = (achievement.value.conditions?.length || 0) + (achievement.value.reward_sources?.length || 0);
          const label = condCount === 1 ? t('condition') : t('conditions');
          tabs.value.push({ name: 'conditions', label });
        } else {
          activeTab.value = 'rewards';
        }

        if (achievement.value.rewards.length) {
          const label = achievement.value.rewards.length === 1 ? t('reward') : t('rewards');
          tabs.value.push({ name: 'rewards', label });
        }

      } 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([fetchAchievement(), fetchCurrency()]);
      } catch (err) {
        console.error('Api error:', err);
      } finally {
        loading.value = false;
      }
    });

    return { loading, error, errorMessage, achievement, activeTab, tabs, currency, route };
  },
});
</script>

<style lang="scss" scoped>
.loyalty-suite-achievement {
  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%;
    flex-direction: column;
  }

  &__progress {
    display: flex;
    flex-direction: column;
    width: 100%;
    max-width: 400px;
    margin-top: 20px;

    &-title {
      display: flex;
      font-size: 14px;
      font-weight: 700;
      margin-bottom: 7px;
    }

    &-value {
      display: flex;
      font-size: 14px;
      text-transform: lowercase;
    }

    &-wrapper {
      display: flex;
      width: 100%;
      height: 4px;
      border-radius: 8px;
      background: var(--loyalty-suite-borders-40);
      position: relative;
      margin: 0 0 7px 0;
    }

    &-bar {
      display: flex;
      position: absolute;
      left: 0;
      top: 0;
      height: 4px;
      border-radius: 8px;
      background: var(--loyalty-suite-positive);
    }
  }

  &__icon {
    display: flex;
    width: 70px;
    height: 70px;
    object-fit: cover;
    margin-bottom: 20px;
  }

  &__image {
    display: flex;
    width: 360px;
    height: 200px;
    object-fit: cover;
    border-radius: 8px;
    margin-bottom: 20px;
  }

  &__title {
    display: flex;
    font-size: 16px;
    font-weight: 700;
    line-height: normal;
  }

  &__description {
    width: 100%;
    margin-top: 20px;

    :deep(p) {
      max-width: 100%;
      font-size: 14px;
      font-style: normal;
      line-height: normal;
      margin-bottom: 16px !important;

      &:last-child {
        margin-bottom: 0 !important;
      }
    }

    :deep(h1),
    :deep(h2),
    :deep(h3),
    :deep(h4),
    :deep(h5),
    :deep(h6) {
      margin-bottom: 16px !important;

      &:last-child {
        margin-bottom: 0 !important;
      }
    }

    :deep(ul),
    :deep(ol) {
      max-width: 100%;
      margin-bottom: 16px;

      &:last-child {
        margin-bottom: 0 !important;
      }

      :deep(li) {
        font-size: 14px;
        font-style: normal;
        line-height: normal;
      }

      &:last-child {
        margin-bottom: 0;
      }
    }

    :deep(a) {
      color: var(--loyalty-suite-primary);
      text-decoration: none;
      transition: 0.3s;

      &:hover {
        color: var(--loyalty-suite-primary-90);
      }
    }

    :deep(iframe),
    :deep(table),
    :deep(video) {
      max-width: 100%;
    }

    :deep(img) {
      max-width: 100%;
      object-fit: cover;
    }
  }

  &__tabs {
    display: flex;
    width: 100%;
    flex-wrap: wrap;
    margin-top: 25px;
    margin-bottom: 15px;

    &-button {
      display: flex;
      margin: 0 10px 10px 0;
      padding: 8px 12px 7px 12px;
      font-size: 14px;
      line-height: normal;
      border-radius: 4px;
      background: var(--loyalty-suite-light);
      outline: 1px solid var(--loyalty-suite-borders-60);
      color: var(--loyalty-suite-dark);
      transition: .3s;
      text-decoration: none;

      &.loyalty-suite-achievement__tabs-button_active {
        color: var(--loyalty-suite-primary);
        outline-color: var(--loyalty-suite-primary);

        &:hover {
          cursor: default;
        }
      }

      &:hover {
        cursor: pointer;
        color: var(--loyalty-suite-primary);
        outline-color: var(--loyalty-suite-primary);
      }

      &:last-child {
        margin-right: 0;
      }
    }
  }

  &__panels {
    display: flex;
    width: 100%;
    margin-bottom: 25px;

    &-container {
      display: flex;
      width: 100%;
      flex-direction: column;
    }
  }

  &__order {
    display: flex;
    width: 100%;
    margin-bottom: 20px;
  }

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

  &__reward-sources {
    display: flex;
    width: 100%;
    flex-direction: column;
    margin-top: -10px;
    margin-bottom: 25px;
    &-item {
      display: flex;
      align-items: center;
      width: 100%;
      margin-bottom: 10px;
      &:last-child {
        margin-bottom: 0;
      }
    }
    a.loyalty-suite-achievement__reward-sources-link {
      align-items: center;
      margin: 0;
      font-size: 14px;
      font-weight: 700;
      line-height: 1;
      color: var(--loyalty-suite-primary);
      transition: 0.3s;
      text-decoration: none !important;
      margin-left: 4px;
      &:hover {
        color: var(--loyalty-suite-primary-90);
      }
    }
  }
}

@media (max-width: 576px) {
  .loyalty-suite-achievement {
    &__header {
      align-items: center;
    }

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