<script setup lang="ts">
import { computed, onBeforeUnmount, onMounted, ref } from 'vue'
import { useRouter } from 'vue-router'

import notFoundImage from '@/assets/images/404NotFound.png'
import { fetchCurrentUser } from '@/services/authSession'

const router = useRouter()
const isAuthenticated = ref(false)
let autoRedirectTimer: ReturnType<typeof setTimeout> | null = null

const redirectRouteName = computed(() => (isAuthenticated.value ? 'Dashboard' : 'Home'))
const redirectButtonLabel = computed(() =>
  isAuthenticated.value ? 'Zum Dashboard' : 'Zur Startseite',
)
const redirectButtonIcon = computed(() =>
  isAuthenticated.value ? 'mdi-view-dashboard-outline' : 'mdi-home-outline',
)
const autoRedirectTargetLabel = computed(() => (isAuthenticated.value ? 'Dashboard' : 'Startseite'))

function clearAutoRedirectTimer() {
  if (autoRedirectTimer === null) {
    return
  }

  clearTimeout(autoRedirectTimer)
  autoRedirectTimer = null
}

function scheduleAutoRedirect() {
  clearAutoRedirectTimer()

  autoRedirectTimer = setTimeout(() => {
    void router.replace({ name: redirectRouteName.value })
  }, 4000)
}

async function resolveRedirectTarget() {
  try {
    const currentUser = await fetchCurrentUser()
    isAuthenticated.value = currentUser !== null
  } catch {
    isAuthenticated.value = false
  }

  scheduleAutoRedirect()
}

function navigateToPrimaryTarget() {
  clearAutoRedirectTimer()
  void router.replace({ name: redirectRouteName.value })
}

function navigateBack() {
  clearAutoRedirectTimer()

  if (window.history.length > 1) {
    router.back()
    return
  }

  void router.push({ name: redirectRouteName.value })
}

onMounted(() => {
  void resolveRedirectTarget()
})

onBeforeUnmount(() => {
  clearAutoRedirectTimer()
})
</script>

<template>
  <v-container fluid class="not-found-page hoard-page hoard-page--centered">
    <section class="not-found-shell hoard-panel hoard-panel-gradient hoard-spotlight hoard-shell-grid">
      <div class="not-found-visual">
        <div class="image-frame">
          <img
            :src="notFoundImage"
            alt="Illustration für eine nicht gefundene Seite"
            class="not-found-image"
          />
        </div>
      </div>

      <div class="not-found-content">
        <p class="not-found-code">404</p>
        <p class="hoard-kicker hoard-kicker--wide">Seite nicht gefunden</p>
        <h1>Diese Spur führt ins Leere.</h1>
        <p class="not-found-text">
          Der Link ist ungültig oder die Seite wurde verschoben. Wir leiten dich gleich zur
          {{ autoRedirectTargetLabel }} weiter – oder du nutzt direkt einen der Buttons unten.
        </p>

        <div class="not-found-actions hoard-action-row">
          <v-btn
            variant="elevated"
            :prepend-icon="redirectButtonIcon"
            @click="navigateToPrimaryTarget"
          >
            {{ redirectButtonLabel }}
          </v-btn>
          <v-btn variant="outlined" prepend-icon="mdi-arrow-left" @click="navigateBack">
            Zurück
          </v-btn>
        </div>

        <p class="not-found-hint">
          <v-icon icon="mdi-clock-time-four-outline" size="14" />
          Auto-Redirect zur {{ autoRedirectTargetLabel }} in wenigen Sekunden.
        </p>
      </div>
    </section>
  </v-container>
</template>

<style scoped>
.not-found-shell {
  --hoard-shell-width: 1040px;
  --hoard-gradient-angle: 130deg;
  --hoard-gradient-start: color-mix(in srgb, var(--color-primary-100) 60%, var(--color-surface) 40%);
  --hoard-gradient-end: var(--color-surface);
  --hoard-gradient-end-stop: 65%;

  grid-template-columns: minmax(260px, 1fr) minmax(320px, 1fr);
  border-radius: var(--radius-xl);
  align-items: center;
}

.not-found-visual {
  display: flex;
  align-items: center;
  justify-content: center;
}

.image-frame {
  position: relative;
  width: min(100%, 380px);
  aspect-ratio: 1 / 1;
  padding: var(--space-5);
  border: 1px solid var(--color-border);
  border-radius: var(--radius-xl);
  background:
    radial-gradient(
      120% 80% at 0% 100%,
      color-mix(in srgb, var(--color-primary-100) 50%, transparent),
      transparent 70%
    ),
    color-mix(in srgb, var(--color-surface-alt) 86%, var(--color-surface) 14%);
  box-shadow: var(--shadow-md);
}

.not-found-image {
  width: 100%;
  height: 100%;
  object-fit: contain;
}

.not-found-content {
  display: flex;
  flex-direction: column;
  justify-content: center;
}

.not-found-code {
  margin: 0 0 var(--space-3);
  font-family: var(--font-family-mono);
  font-size: 88px;
  font-weight: 700;
  letter-spacing: -0.05em;
  line-height: 1;
  background: linear-gradient(135deg, var(--color-primary-700), var(--color-primary-500) 60%, var(--color-accent-lime) 100%);
  -webkit-background-clip: text;
  background-clip: text;
  color: transparent;
}

h1 {
  margin: 0 0 var(--space-3);
  font-size: clamp(1.8rem, 1.4rem + 1vw, 2.4rem);
  font-weight: 700;
  letter-spacing: -0.02em;
}

.not-found-text {
  margin: 0 0 var(--space-5);
  max-width: 48ch;
  color: var(--color-text-secondary);
  font-size: var(--font-size-md);
  line-height: 1.6;
}

.not-found-actions {
  align-items: center;
}

.not-found-hint {
  display: inline-flex;
  align-items: center;
  gap: var(--space-2);
  margin: var(--space-5) 0 0;
  color: var(--color-text-muted);
  font-size: var(--font-size-xs);
}

.not-found-hint .v-icon {
  color: var(--color-primary-700);
}

@media (prefers-reduced-motion: no-preference) {
  .not-found-visual,
  .not-found-content {
    animation: hoard-soft-enter 320ms both;
  }

  .not-found-content {
    animation-delay: 100ms;
  }
}

@media (width <= 960px) {
  .not-found-shell {
    grid-template-columns: 1fr;
  }

  .image-frame {
    width: min(100%, 320px);
  }

  .not-found-content {
    text-align: center;
    align-items: center;
  }

  .not-found-actions {
    justify-content: center;
    gap: var(--space-2);
  }

  :deep(.not-found-actions .v-btn) {
    min-height: 44px;
  }
}

@media (width <= 600px) {
  .not-found-code {
    font-size: 64px;
  }

  .not-found-text {
    font-size: var(--font-size-md);
  }

  .image-frame {
    width: min(100%, 260px);
    padding: var(--space-4);
  }

  .not-found-actions {
    width: 100%;
    display: grid;
    grid-template-columns: 1fr;
  }

  :deep(.not-found-actions .v-btn) {
    width: 100%;
  }
}
</style>
