<template>
  <div class="splash-screen">
    <div class="splash-content">
      <!-- Logo with animation -->
      <div class="logo-container" :class="{ 'logo-visible': logoVisible }">
        <div class="logo-box">
          <img src="/icon-192.png" alt="SIBU" class="logo-icon" />
        </div>
      </div>

      <!-- Loading indicator -->
      <div v-if="showLoading" class="loading-container" :class="{ 'loading-visible': loadingVisible }">
        <div class="spinner"></div>
        <p class="status-message">{{ statusMessage }}</p>
      </div>
    </div>

    <!-- Version info -->
    <div class="version-info">
      <p class="app-subtitle">Transporte Público Boquete</p>
      <p class="app-version">Versión 2.0.0</p>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useRouteStore } from '@/stores/route'
import { useBusStopStore } from '@/stores/busStop'
import { supabase } from '@/supabase'

const router = useRouter()
const routeStore = useRouteStore()
const busStopStore = useBusStopStore()

const logoVisible = ref(false)
const showLoading = ref(false)
const loadingVisible = ref(false)
const statusMessage = ref('Iniciando SIBU...')

onMounted(async () => {
  logoVisible.value = true
  showLoading.value = true
  loadingVisible.value = true

  const initTimeout = setTimeout(() => {
    console.warn('Initialization taking too long, forcing navigation...')
    statusMessage.value = 'Iniciando de todas formas...'
    navigate()
  }, 5000)

  try {
    await performInitializationTasks()
    clearTimeout(initTimeout)
    navigate()
  } catch (error) {
    console.error('Initialization failed', error)
    clearTimeout(initTimeout)
    navigate()
  }
})

async function navigate() {
  const { data: { session } } = await supabase.auth.getSession()

  if (!session) {
    router.replace('/map')
    return
  }

  const { data: profile } = await supabase
    .from('users')
    .select('role')
    .eq('id', session.user.id)
    .single()

  const role = profile?.role?.toUpperCase()
  if (role === 'ADMIN') router.replace('/admin')
  else if (role === 'DRIVER') router.replace('/driver')
  else if (role === 'PROMOTER') router.replace('/promoter')
  else router.replace('/map')
}

async function performInitializationTasks() {
  statusMessage.value = 'Verificando sesión...'

  statusMessage.value = 'Cargando datos de rutas...'
  try { await routeStore.loadRoutes() } catch (e) { console.error(e) }

  statusMessage.value = 'Cargando paradas...'
  try { await busStopStore.loadBusStops() } catch (e) { console.error(e) }

  statusMessage.value = 'Listo para usar'
}
</script>

<style scoped>
.splash-screen {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100vh;
  background-color: #101820;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  z-index: 9999;
}
.splash-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  flex: 1;
}
.logo-container {
  opacity: 0;
  transform: scale(0.8);
  transition: opacity 0.6s ease-out, transform 0.8s cubic-bezier(0.34, 1.56, 0.64, 1);
}
.logo-container.logo-visible {
  opacity: 1;
  transform: scale(1);
}
.logo-box {
  width: 140px;
  height: 140px;
  background-color: #fee715;
  border-radius: 28px;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 8px 20px rgba(0, 0, 0, 0.2);
}
.logo-icon {
  width: 100%;
  height: 100%;
  object-fit: contain;
  display: block;
}
.loading-container {
  margin-top: 48px;
  display: flex;
  flex-direction: column;
  align-items: center;
  opacity: 0;
  transition: opacity 0.8s ease-in;
}
.loading-container.loading-visible { opacity: 1; }
.spinner {
  width: 32px;
  height: 32px;
  border: 3px solid rgba(254, 231, 21, 0.3);
  border-top-color: #fee715;
  border-radius: 50%;
  animation: spin 0.8s linear infinite;
}
@keyframes spin { to { transform: rotate(360deg); } }
.status-message {
  margin-top: 16px;
  color: rgba(255, 255, 255, 0.8);
  font-size: 14px;
  text-align: center;
}
.version-info {
  position: absolute;
  bottom: 64px;
  left: 0;
  right: 0;
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 8px;
}
.app-subtitle {
  color: rgba(255, 255, 255, 0.6);
  font-size: 12px;
  text-align: center;
}
.app-version {
  color: rgba(255, 255, 255, 0.4);
  font-size: 10px;
  text-align: center;
}
@media (max-width: 480px) {
  .logo-box { width: 120px; height: 120px; border-radius: 24px; }
  .loading-container { margin-top: 40px; }
  .version-info { bottom: 48px; }
}
</style>
