<script setup lang="ts">
import { ref, onMounted, onUnmounted, watch } from 'vue'
import { useI18n } from 'vue-i18n'
import { useScheduleStore } from '@/stores/schedule'
import { useRouteStore } from '@/stores/route'
import { formatTo12Hour } from '@/utils/timeFormatter'
import { analyticsService } from '@/services/analyticsService'

import { useRouter, useRoute } from 'vue-router'

const { t } = useI18n()
const route = useRoute()
const router = useRouter()

const scheduleStore = useScheduleStore()
const routeStore = useRouteStore()

const showRouteDropdown = ref(false)
const routeCardRef = ref<HTMLElement | null>(null)

// Close dropdown when clicking outside
function handleClickOutside(event: MouseEvent) {
  if (routeCardRef.value && !routeCardRef.value.contains(event.target as Node)) {
    showRouteDropdown.value = false
  }
}

onMounted(async () => {
  analyticsService.logEvent({ event_name: 'screen_view', screen_name: 'Schedules' })
  document.addEventListener('click', handleClickOutside)
  await routeStore.loadRoutes()

  // Point 1: Smart synchronization from MapView
  const queryRouteId = route.query.routeId as string
  if (queryRouteId) {
    const foundRoute = routeStore.allRoutes.find(r => r.id === queryRouteId)
    if (foundRoute) {
      // FIX: Use sync function to avoid redirect loop back to map
      syncRouteSelection(foundRoute.id, foundRoute.name)
    }
  }
})

const unwatchQuery = watch(
  () => route.query.routeId,
  (newRouteId) => {
    if (newRouteId) {
      const foundRoute = routeStore.allRoutes.find(r => r.id === newRouteId as string)
      if (foundRoute) {
        syncRouteSelection(foundRoute.id, foundRoute.name)
      }
    }
  }
)

onUnmounted(() => {
  document.removeEventListener('click', handleClickOutside)
  unwatchQuery()
})

function syncRouteSelection(routeId: string, routeName: string) {
  routeStore.selectRoute(routeId, routeName)
  scheduleStore.loadRouteSchedules(routeId)
  showRouteDropdown.value = false
}

function selectRouteAndClose(routeId: string, routeName: string) {
  analyticsService.logEvent({ 
    event_name: 'schedule_viewed', 
    item_id: routeName,
    properties: { route_id: routeId }
  })
  
  routeStore.selectRoute(routeId, routeName)
  scheduleStore.loadRouteSchedules(routeId)
  showRouteDropdown.value = false
}

function goToMap() {
  if (routeStore.selectedRouteId) {
    router.push({ 
      path: '/map', 
      query: { routeId: routeStore.selectedRouteId } 
    })
  }
}

function clearRouteAndClose() {
  routeStore.clearSelection()
  scheduleStore.schedules = []
  showRouteDropdown.value = false
}
</script>

<template>
  <div class="schedules-view">
    <h1>{{ t('schedules.title') }}</h1>
    
    <div v-if="routeStore.isLoadingRoutes">
      <p>{{ t('schedules.loadingRoutes') }}</p>
    </div>
    
    <div v-else-if="routeStore.allRoutes.length === 0">
      <p>{{ t('schedules.noRoutesAvailable') }}</p>
    </div>
    
    <div v-else>
      <!-- Quick Select Route Buttons (Nexus Style) -->
      <div class="quick-routes-container">
        <div 
          v-for="route in routeStore.allRoutes" 
          :key="route.id"
          class="route-chip-nexus"
          :class="{ 'active': route.id === routeStore.selectedRouteId }"
          @click="selectRouteAndClose(route.id, route.name)"
        >
          <span class="material-icons chip-icon">directions_bus</span>
          <span class="chip-text">{{ route.name }}</span>
          <div v-if="route.id === routeStore.selectedRouteId" class="active-dot"></div>
        </div>
      </div>

      <!-- Route selector card (As backup/dropdown) -->
      <div class="route-card" ref="routeCardRef">
        <div class="route-card-content" @click.stop="showRouteDropdown = !showRouteDropdown">
          <span class="material-icons route-icon">search</span>
          <div class="route-info">
            <div v-if="routeStore.selectedRouteId && routeStore.selectedRouteName" class="route-name">
              {{ routeStore.selectedRouteName }}
            </div>
            <div v-else class="route-name">Buscar otra ruta...</div>
          </div>
          <span class="material-icons arrow-icon" :class="{ 'rotated': showRouteDropdown }">
            keyboard_arrow_down
          </span>
        </div>
        
        <!-- Dropdown menu -->
        <div v-if="showRouteDropdown" class="route-dropdown" @click.stop>
          <div
            v-for="route in routeStore.allRoutes"
            :key="route.id"
            class="route-option"
            :class="{ 'selected': route.id === routeStore.selectedRouteId }"
            @click="selectRouteAndClose(route.id, route.name)"
          >
            {{ route.name }}
          </div>
        </div>
      </div>
      
      <div v-if="routeStore.selectedRouteId" class="schedules-content">
        <div class="schedules-header">
          <h2 v-if="routeStore.selectedRouteName">{{ routeStore.selectedRouteName }}</h2>
          <button class="view-route-btn" @click="goToMap">
            <span class="material-icons">map</span>
            Ver ruta
          </button>
        </div>
        
        <div v-if="scheduleStore.isLoading" class="schedules-loading">
          <span class="material-icons spin">refresh</span>
          <p>Cargando horarios...</p>
        </div>
        
        <div v-else-if="scheduleStore.error" class="schedules-error">
          <p>{{ scheduleStore.error }}</p>
        </div>
        
        <div v-else-if="scheduleStore.schedules.length > 0">
          <ul class="schedule-list">
            <li v-for="schedule in scheduleStore.schedules" :key="schedule.id" class="schedule-item">
              <div class="schedule-item-info">
                <span class="material-icons">schedule</span>
                <span class="departure-time">{{ formatTo12Hour(schedule.departure_time) }}</span>
              </div>
              <span class="schedule-type">{{ schedule.schedule_type }}</span>
            </li>
          </ul>
        </div>
        
        <div v-else class="schedules-empty">
          <span class="material-icons">event_busy</span>
          <p>No hay horarios disponibles para esta ruta.</p>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
.schedules-view {
  min-height: 100vh;
  position: relative;
  padding: 1.5rem 1rem 150px;
  color: var(--text-primary);
  overflow-x: hidden;
  background: var(--bg-primary) !important;
}


/* Asegurar que el contenido flote sobre el fondo */
.schedules-view > * {
  position: relative;
  z-index: 1;
}

.schedules-view h1 {
  font-size: 2.2rem;
  font-weight: 800;
  text-shadow: 0 2px 10px rgba(0,0,0,0.3);
  margin-bottom: 2rem;
  text-align: center;
}

.quick-routes-container {
  display: flex;
  flex-wrap: wrap;
  justify-content: center;
  gap: 12px;
  margin-bottom: 24px;
  max-width: 800px;
  margin-left: auto;
  margin-right: auto;
}

.route-chip-nexus {
  background: rgba(255, 255, 255, 0.05);
  border: 1px solid var(--border-color);
  padding: 12px 20px;
  border-radius: 16px;
  display: flex;
  align-items: center;
  gap: 10px;
  cursor: pointer;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  position: relative;
  overflow: hidden;
}

.route-chip-nexus:hover {
  background: rgba(254, 231, 21, 0.1);
  border-color: var(--active-color);
  transform: translateY(-2px);
}

.route-chip-nexus.active {
  background: var(--active-color);
  border-color: var(--active-color);
  color: #101820;
  box-shadow: 0 8px 20px rgba(254, 231, 21, 0.3);
}

.chip-icon {
  font-size: 20px;
  color: var(--active-color);
}

.route-chip-nexus.active .chip-icon {
  color: #101820;
}

.chip-text {
  font-weight: 800;
  font-size: 0.9rem;
  letter-spacing: 0.5px;
}

.active-dot {
  position: absolute;
  top: 6px;
  right: 6px;
  width: 6px;
  height: 6px;
  background: #101820;
  border-radius: 50%;
}

.route-card {
  margin-bottom: 2rem;
  max-width: 400px;
  margin-left: auto;
  margin-right: auto;
}

.route-card-content {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 18px;
  background: var(--card-bg);
  backdrop-filter: blur(16px);
  -webkit-backdrop-filter: blur(16px);
  border: 1px solid var(--border-color);
  border-radius: 16px;
  box-shadow: var(--shadow);
  cursor: pointer;
  transition: transform 0.2s ease, box-shadow 0.3s ease;
}

.route-card-content:hover {
  transform: translateY(-2px);
  box-shadow: 0 12px 30px rgba(0,0,0,0.2);
}

.route-card-content:active {
  transform: scale(0.98);
}

.route-icon {
  color: var(--active-color);
  font-size: 28px;
}

.route-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 2px;
}

.route-name {
  font-size: 1.1rem;
  font-weight: 700;
  color: var(--text-primary);
}

.route-stops {
  font-size: 0.9rem;
  color: var(--text-secondary);
  font-weight: 500;
}

.arrow-icon {
  color: var(--text-secondary);
  font-size: 24px;
  transition: transform 0.3s cubic-bezier(0.4, 0, 0.2, 1);
}

.arrow-icon.rotated {
  transform: rotate(180deg);
  color: var(--active-color);
}

.route-dropdown {
  position: absolute;
  top: 100%;
  left: 0;
  right: 0;
  margin-top: 10px;
  background: var(--card-bg);
  backdrop-filter: blur(20px);
  -webkit-backdrop-filter: blur(20px);
  border: 1px solid var(--border-color);
  border-radius: 16px;
  box-shadow: var(--shadow);
  max-height: 250px;
  overflow-y: auto;
  z-index: 100;
}

.route-option {
  padding: 14px 20px;
  cursor: pointer;
  transition: all 0.2s ease;
  border-bottom: 1px solid var(--border-color);
  color: var(--text-primary);
  font-weight: 500;
}

.route-option:last-child {
  border-bottom: none;
}

.route-option:hover {
  background-color: var(--hover-bg);
  padding-left: 24px;
}

.route-option.selected {
  background-color: var(--active-bg);
  color: var(--active-color);
  font-weight: 700;
}

.route-option.clear-option {
  color: #ef4444; /* Rojo para limpiar */
  font-weight: 600;
  text-align: center;
}

.schedules-content {
  margin-top: 1.5rem;
  background: var(--card-bg);
  backdrop-filter: blur(16px);
  -webkit-backdrop-filter: blur(16px);
  padding: 24px;
  border: 1px solid var(--border-color);
  border-radius: 24px;
  box-shadow: var(--shadow);
  max-width: 800px;
  margin-left: auto;
  margin-right: auto;
}

.schedules-content h2 {
  text-align: center;
  margin-bottom: 1.5rem;
  color: var(--active-color);
  font-size: 1.5rem;
  font-weight: 800;
}

.schedules-loading, .schedules-empty, .schedules-error {
  text-align: center;
  padding: 40px 20px;
}

.spin {
  animation: spin 1s linear infinite;
  font-size: 3rem;
  color: var(--active-color);
  margin-bottom: 16px;
  display: inline-block;
}

@keyframes spin {
  from { transform: rotate(0deg); }
  to { transform: rotate(360deg); }
}

.schedule-list {
  list-style: none;
  padding: 0;
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  gap: 16px;
}

.schedule-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 16px 20px;
  background: var(--bg-secondary);
  border-radius: 16px;
  border: 1px solid var(--border-color);
  transition: all 0.2s ease;
  box-shadow: 0 4px 12px rgba(0,0,0,0.05);
}

.schedule-item:hover {
  transform: translateY(-3px) scale(1.02);
  border-color: var(--active-color);
  box-shadow: 0 8px 20px rgba(0,0,0,0.1);
}

.schedule-item-info {
  display: flex;
  align-items: center;
  gap: 12px;
}

.schedule-item .material-icons {
  color: var(--active-color);
}

.departure-time {
  font-size: 1.3rem;
  font-weight: 800;
  color: var(--text-primary);
  letter-spacing: -0.5px;
}

.schedule-type {
  font-size: 0.75rem;
  font-weight: 700;
  padding: 5px 10px;
  background: var(--active-bg);
  color: var(--active-color);
  border-radius: 8px;
  text-transform: uppercase;
  letter-spacing: 0.5px;
}

.schedules-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 2rem;
  gap: 16px;
  flex-wrap: wrap;
}

.schedules-header h2 {
  margin-bottom: 0 !important;
  text-align: left !important;
  flex: 1;
}

.view-route-btn {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 12px 24px;
  background: #FEE715;
  color: #101820;
  border: none;
  border-radius: 12px;
  font-weight: 700;
  cursor: pointer;
  transition: all 0.3s ease;
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.2);
}

.view-route-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 6px 20px rgba(0, 0, 0, 0.3);
  filter: brightness(1.1);
}

.view-route-btn:active {
  transform: translateY(0);
}

@media (max-width: 600px) {
  .schedules-header {
    flex-direction: column;
    text-align: center;
  }
  .schedules-header h2 {
    text-align: center !important;
  }
  .view-route-btn {
    width: 100%;
    justify-content: center;
  }
}
</style>

