<template>
  <div class="loyalty-suite">
    <NotLoggedIn v-if="!IsUserLoggedIn && !isSharePage" />
    <div
      class="loyalty-suite-navigation"
      v-if="!isSharePage"
    >
      <Navigation v-if="!loadingNavigation" :data="navigationData" />
    </div>
    <router-view />
  </div>
</template>

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

export default defineComponent({
  components: { Navigation, NotLoggedIn },
  setup() {
    const apiRoutes = window.loyalty_suite_account_data.apiRoutes;
    const IsUserLoggedIn = window.loyalty_suite_account_data.isUserLoggedIn;
    const nonce = window.loyalty_suite_account_data.nonce;
    const loadingNavigation = ref(true);
    const navigationData = ref({
      sections: {
        ranks: false,
        achievements: false,
        challenges: false,
      },
      notifications: {
        profile: false,
        ranks: false,
        achievements: false,
        challenges: false,
      },
    });

    const route = useRoute();
    const isSharePage = computed(() => route.path === '/share' || route.path === '/share/' );

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

        if (!res.ok) throw new Error(`API Error: ${res.status}`);

        navigationData.value = await res.json();
      } catch (e) {
        console.error('Navigation error:', e);
      } finally {
        loadingNavigation.value = false;
      }
    };

    onBeforeMount(fetchNavigationData);

    return {
      navigationData,
      loadingNavigation,
      IsUserLoggedIn,
      isSharePage,
    };
  },
});
</script>
