<script setup>
import { useRoute } from "vue-router";
import { computed, ref, onMounted } from "vue";
import { useAuth } from "../../composables/useAuth.js";
import accessDeniedImg from "../../assets/images/landing/access-denied.png";

const route = useRoute();
const { isAuthenticated } = useAuth();

const DEFAULT_MESSAGE = "You don't have permission to access this page.";

// Message from sessionStorage (set by API interceptor or router guard; keeps URL clean)
const storedMessage = ref(null);

onMounted(() => {
  if (typeof sessionStorage === "undefined") return;
  const raw = sessionStorage.getItem("accessDeniedMessage");
  if (raw) {
    storedMessage.value = raw;
    sessionStorage.removeItem("accessDeniedMessage");
  }
});

// Fallback: message from URL query (e.g. old links or other redirects)
const queryMessage = computed(() => {
  const raw = route.query.message;
  if (!raw || typeof raw !== "string") return null;
  try {
    return decodeURIComponent(raw);
  } catch {
    return null;
  }
});

const displayMessage = computed(
  () => storedMessage.value || queryMessage.value || DEFAULT_MESSAGE,
);
</script>

<template>
  <section
    class="animate-fadein animate-duration-300 animate-ease-in landing-container mx-auto min-h-[75vh] lg:min-h-screen flex flex-col items-center justify-center"
  >
    <img
      class="w-[15rem]"
      :src="accessDeniedImg"
      alt="Access denied"
    />
    <h1 class="title-h5 lg:title-h1 mt-8">Access Denied</h1>
    <p class="body-small lg:body-large mt-2 lg:mt-4">
      {{ displayMessage }}
    </p>
    <router-link
      v-if="isAuthenticated"
      to="/dashboard"
      class="body-button bg-violet-600 w-fit mt-8 hover:bg-violet-500 px-4"
      >Go to Dashboard</router-link
    >
    <router-link
      v-else
      to="/login"
      class="body-button bg-violet-600 w-fit mt-8 hover:bg-violet-500 px-4"
      >Go to Login</router-link
    >
  </section>
</template>
