<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()

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

  const queryRouteId = route.query.routeId as string
  if (queryRouteId) {
    const foundRoute = routeStore.allRoutes.find(r => r.id === queryRouteId)
    if (foundRoute) {
      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(() => {
  unwatchQuery()
})

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

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)
}

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

<template>
  <div class="schedules-view">

    <!-- Selector de Línea -->
    <div class="route-selector-section">
      <div v-if="routeStore.isLoadingRoutes" class="state-row">
        <div class="spinner-sm"></div>
        <span class="state-label">{{ t('schedules.loadingRoutes') }}</span>
      </div>

      <div v-else-if="routeStore.allRoutes.length > 0" class="selector-wrapper">
        <label class="selector-label">{{ t('schedules.selectRoute') || 'Seleccionar Línea' }}</label>
        <div class="select-container">
          <select 
            class="route-select"
            id="route-select"
            :value="routeStore.selectedRouteId"
            @change="e => {
              const target = e.target as HTMLSelectElement;
              if (target) {
                const selectedRoute = routeStore.allRoutes.find(r => r.id === target.value);
                if (selectedRoute) selectRouteAndClose(target.value, selectedRoute.name);
              }
            }"
          >
            <option value="" disabled>{{ t('schedules.placeholder') || 'Elige una ruta...' }}</option>
            <option v-for="r in routeStore.allRoutes" :key="r.id" :value="r.id">
              {{ r.name }}
            </option>
          </select>
          <span class="material-icons select-chevron">expand_more</span>
        </div>
      </div>
    </div>

    <!-- Contenido principal -->
    <main class="schedules-main">

      <!-- Sin ruta seleccionada -->
      <div v-if="!routeStore.selectedRouteId && !routeStore.isLoadingRoutes" class="empty-state">
        <span class="material-icons empty-icon">route</span>
        <p class="empty-text">Selecciona una ruta para ver sus horarios</p>
      </div>

      <template v-else-if="routeStore.selectedRouteId">
        <!-- Encabezado de sección -->
        <div class="section-header">
          <h2 class="section-title">{{ t('schedules.upcoming') || 'Próximas salidas' }}</h2>
          <div class="live-badge">
            <span class="live-dot"></span>
            <span class="live-text">EN VIVO</span>
          </div>
        </div>

        <!-- Cargando horarios -->
        <div v-if="scheduleStore.isLoading" class="state-row center">
          <div class="spinner-sm"></div>
        </div>

        <!-- Sin horarios -->
        <div v-else-if="scheduleStore.schedules.length === 0" class="no-schedules-card">
          <span class="material-icons no-schedule-icon">event_busy</span>
          <p class="no-schedule-text">{{ t('schedules.noSchedules') || 'No hay salidas programadas para hoy' }}</p>
        </div>

        <!-- Lista de horarios -->
        <div v-else class="schedules-list">
          <div 
            v-for="schedule in scheduleStore.schedules" 
            :key="schedule.id" 
            class="schedule-card"
          >
            <div class="schedule-left">
              <div class="departure-time">
                {{ formatTo12Hour(schedule.departure_time) }}
              </div>
              <div class="divider-v"></div>
              <div class="schedule-info">
                <p class="schedule-label">Línea</p>
                <p class="schedule-route-name">{{ routeStore.selectedRouteName }}</p>
              </div>
            </div>

            <span 
              class="schedule-type-badge"
              :class="schedule.schedule_type === 'weekday' ? 'badge-weekday' : 'badge-other'"
            >
              {{ t(`schedules.types.${schedule.schedule_type}`) || schedule.schedule_type }}
            </span>
          </div>
        </div>
      </template>
    </main>

    <!-- Botón flotante: ir al mapa -->
    <Transition name="fab">
      <button 
        v-if="routeStore.selectedRouteId"
        @click="goToMap"
        class="fab-map"
        title="Ver en el mapa"
      >
        <span class="material-icons">map</span>
      </button>
    </Transition>
  </div>
</template>

<style scoped>
.schedules-view {
  display: flex;
  flex-direction: column;
  min-height: 100%;
  background: var(--bg-primary);
  color: var(--text-primary);
  padding-bottom: 6rem;
  position: relative;
}

/* ─── Selector de ruta ─── */
.route-selector-section {
  padding: 1rem 1.25rem 0.75rem;
  border-bottom: 1px solid var(--border-color);
  background: var(--bg-primary);
  position: sticky;
  top: 0;
  z-index: 10;
}

.state-row {
  display: flex;
  align-items: center;
  gap: 0.75rem;
  padding: 0.5rem 0;
}

.state-row.center {
  justify-content: center;
  padding: 2.5rem 0;
}

.state-label {
  color: var(--text-secondary);
  font-size: 0.875rem;
  font-weight: 600;
}

.selector-wrapper {
  display: flex;
  flex-direction: column;
  gap: 0.375rem;
}

.selector-label {
  font-size: 0.625rem;
  font-weight: 800;
  color: var(--text-secondary);
  letter-spacing: 0.1em;
  text-transform: uppercase;
  padding-left: 0.25rem;
}

.select-container {
  position: relative;
}

.route-select {
  width: 100%;
  padding: 0.875rem 3rem 0.875rem 1rem;
  background: var(--bg-secondary);
  border: 1.5px solid var(--border-color);
  border-radius: 1rem;
  color: var(--text-primary);
  font-size: 1rem;
  font-weight: 700;
  font-family: inherit;
  cursor: pointer;
  appearance: none;
  transition: border-color 0.2s;
  outline: none;
}

.route-select:focus {
  border-color: var(--active-color);
}

.route-select option {
  background: var(--bg-secondary);
  color: var(--text-primary);
}

.select-chevron {
  position: absolute;
  right: 0.875rem;
  top: 50%;
  transform: translateY(-50%);
  color: var(--text-secondary);
  pointer-events: none;
}

/* ─── Contenido ─── */
.schedules-main {
  flex: 1;
  padding: 1rem 1.25rem;
}

/* ─── Estado vacío ─── */
.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 5rem 1rem;
  gap: 0.75rem;
  text-align: center;
}

.empty-icon {
  font-size: 4rem;
  color: var(--border-color);
}

.empty-text {
  color: var(--text-secondary);
  font-size: 0.9375rem;
  font-style: italic;
  margin: 0;
}

/* ─── Encabezado sección ─── */
.section-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 1rem;
}

.section-title {
  font-size: 0.8125rem;
  font-weight: 700;
  color: var(--text-secondary);
  margin: 0;
  text-transform: uppercase;
  letter-spacing: 0.05em;
}

.live-badge {
  display: flex;
  align-items: center;
  gap: 0.375rem;
  background: rgba(254, 231, 21, 0.1);
  border-radius: 999px;
  padding: 0.25rem 0.625rem;
}

.live-dot {
  width: 0.4375rem;
  height: 0.4375rem;
  border-radius: 50%;
  background: var(--active-color);
  animation: pulse 1.5s infinite;
}

@keyframes pulse {
  0%, 100% { opacity: 1; }
  50% { opacity: 0.4; }
}

.live-text {
  font-size: 0.625rem;
  font-weight: 900;
  color: var(--active-color);
  letter-spacing: 0.08em;
}

/* ─── Sin horarios ─── */
.no-schedules-card {
  background: var(--bg-secondary);
  border: 1px solid var(--border-color);
  border-radius: 1rem;
  padding: 2rem;
  text-align: center;
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 0.5rem;
}

.no-schedule-icon {
  font-size: 2.5rem;
  color: var(--border-color);
}

.no-schedule-text {
  color: var(--text-secondary);
  font-size: 0.875rem;
  margin: 0;
}

/* ─── Lista de horarios ─── */
.schedules-list {
  display: flex;
  flex-direction: column;
  gap: 0.75rem;
}

.schedule-card {
  background: var(--bg-secondary);
  border: 1px solid var(--border-color);
  border-radius: 1rem;
  padding: 1rem;
  display: flex;
  align-items: center;
  justify-content: space-between;
  transition: border-color 0.2s;
  animation: slideUp 0.35s ease-out both;
}

.schedule-card:hover {
  border-color: var(--active-color);
}

@keyframes slideUp {
  from { opacity: 0; transform: translateY(8px); }
  to   { opacity: 1; transform: translateY(0); }
}

.schedule-left {
  display: flex;
  align-items: center;
  gap: 0.875rem;
}

.departure-time {
  font-size: 1.75rem;
  font-weight: 900;
  color: var(--text-primary);
  letter-spacing: -0.04em;
  line-height: 1;
}

.divider-v {
  width: 1px;
  height: 2rem;
  background: var(--border-color);
}

.schedule-info {
  display: flex;
  flex-direction: column;
  gap: 0.125rem;
}

.schedule-label {
  font-size: 0.625rem;
  font-weight: 700;
  color: var(--text-secondary);
  text-transform: uppercase;
  letter-spacing: 0.08em;
  margin: 0;
}

.schedule-route-name {
  font-size: 0.9375rem;
  font-weight: 800;
  color: var(--text-primary);
  margin: 0;
  line-height: 1.2;
}

/* ─── Badge tipo de horario ─── */
.schedule-type-badge {
  padding: 0.25rem 0.625rem;
  border-radius: 999px;
  font-size: 0.625rem;
  font-weight: 800;
  text-transform: uppercase;
  letter-spacing: 0.06em;
  white-space: nowrap;
}

.badge-weekday {
  background: rgba(74, 222, 128, 0.12);
  color: #4ade80;
}

.badge-other {
  background: var(--border-color);
  color: var(--text-secondary);
}

/* ─── Spinner ─── */
.spinner-sm {
  width: 2rem;
  height: 2rem;
  border: 2.5px solid var(--border-color);
  border-top-color: var(--active-color);
  border-radius: 50%;
  animation: spin 0.8s linear infinite;
}

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

/* ─── FAB mapa ─── */
.fab-map {
  position: fixed;
  bottom: 5.5rem;
  right: 1.25rem;
  width: 3.5rem;
  height: 3.5rem;
  background: var(--active-color);
  color: #101820;
  border: none;
  border-radius: 50%;
  box-shadow: 0 4px 20px rgba(0,0,0,0.25);
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  z-index: 40;
  transition: transform 0.15s;
}

.fab-map:active {
  transform: scale(0.94);
}

.fab-map .material-icons {
  font-size: 1.5rem;
}

/* ─── Transición FAB ─── */
.fab-enter-active, .fab-leave-active {
  transition: opacity 0.25s ease, transform 0.25s ease;
}
.fab-enter-from, .fab-leave-to {
  opacity: 0;
  transform: translateY(1rem) scale(0.9);
}
</style>
