<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="/icono.png" alt="SIB" 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">{{ t('splash.subtitle') }}</p>
      <p class="app-version">Versión 2.0.1</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'
import { useI18n } from 'vue-i18n'

const router = useRouter()
const { t } = useI18n()
const routeStore = useRouteStore()
const busStopStore = useBusStopStore()

const logoVisible = ref(false)
const showLoading = ref(false)
const loadingVisible = ref(false)
const statusMessage = ref(t('splash.starting'))

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

  // Timeout logic
  const initTimeout = setTimeout(() => {
    console.warn('Initialization taking too long, forcing navigation...')
    statusMessage.value = t('splash.offline')
    router.replace('/map')
  }, 4000)

  try {
    // Start map background initialization without waiting
    performInitializationTasks()
    
    const resp = await supabase.auth.getSession()
    
    clearTimeout(initTimeout)
    navigate(resp.data.session)
  } catch (error) {
    console.error('Initialization failed', error)
    clearTimeout(initTimeout)
    navigate(null, true)
  }
})

async function navigate(sessionData?: any, force = false) {
  let session = sessionData;
  
  if (!session && !force) {
    try {
      const resp = await supabase.auth.getSession()
      session = resp.data.session
    } catch (e) {
      console.warn('Silent auth check failed', e)
    }
  }

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

  // Get the role directly from user metadata for speed
  const role = session.user?.user_metadata?.role?.toUpperCase() || 'PASSENGER'
  
  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 = t('splash.verifying')
  console.log('Starting initialization tasks...')

  // Load essential map data in parallel to save time
  try {
    const start = Date.now()
    await Promise.all([
      routeStore.loadRoutes().then(() => console.log('Routes loaded')),
      busStopStore.loadBusStops().then(() => console.log('Bus stops loaded'))
    ])
    console.log(`Initialization tasks finished in ${Date.now() - start}ms`)
  } catch (e) {
    console.error('Error pre-loading map data', e)
  }

  statusMessage.value = t('splash.ready')
}
</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: transparent;
  border-radius: 0;
  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>
