<script setup lang="ts">
import { onMounted, onUnmounted, ref, computed } from 'vue'
import { useRouter } from 'vue-router'
import { useI18n } from 'vue-i18n'
import { useShuttleStore } from '@/stores/shuttle'
import AuthGuard from '@/components/common/AuthGuard.vue'
import AppImage from '@/components/AppImage.vue'
import { analyticsService } from '@/services/analyticsService'
import LoadingBranded from '@/components/common/LoadingBranded.vue'

const { t } = useI18n()
const shuttleStore = useShuttleStore()
const router = useRouter()

const shuttleCategoryFilter = ref('all')
const shuttleTypeFilter = ref('all')

const filteredShuttles = computed(() => {
  return shuttleStore.shuttles.filter(shuttle => {
    const matchesCategory = shuttleCategoryFilter.value === 'all' || shuttle.category === shuttleCategoryFilter.value
    const matchesType = shuttleTypeFilter.value === 'all' || shuttle.trip_type === shuttleTypeFilter.value
    return matchesCategory && matchesType
  })
})

const verDetalle = (shuttleId: string, shuttleName: string) => {
    analyticsService.logEvent({
      event_name: 'view_details',
      entity_type: 'shuttle',
      entity_id: shuttleId,
      entity_name: shuttleName
    })
    router.push({
        name: 'ShuttleDetalle',
        params: { id: shuttleId }
    })
}

function fetchData() {
    shuttleStore.loadShuttles()
}

function handleRefocus() {
    // Recarga silenciosa: no congela la UI si ya hay datos
    shuttleStore.silentReload()
}

onMounted(async () => {
    analyticsService.logEvent({ event_name: 'screen_view', screen_name: 'ViajesTuristicos' })
    window.addEventListener('app-refocus', handleRefocus)
    if(shuttleStore.shuttles.length === 0) {
        await fetchData()
    }
})

onUnmounted(() => {
    window.removeEventListener('app-refocus', handleRefocus)
})
</script>

<template>
  <div class="viajes-turisticos">
    <!-- FILTROS PREMIUM -->
    <div class="filters-container">
      <div class="filter-card glass-effect">
        <div class="selectors-side">
          <!-- Ruta Select -->
          <div class="select-group-premium">
            <div class="group-content">
              <label>{{ t('shuttle.category') || 'Categoría' }}</label>
              <select v-model="shuttleCategoryFilter">
                <option value="all">{{ t('shuttle.allAreas') || 'Todas las áreas' }}</option>
                <option value="local">Local</option>
                <option value="interprovincial">Interprovincial</option>
              </select>
            </div>
          </div>

          <!-- Tipo de Viaje Select -->
          <div class="select-group-premium">
            <div class="group-content">
              <label>{{ t('shuttle.tripType') }}</label>
              <select v-model="shuttleTypeFilter">
                <option value="all">{{ t('shuttle.tripType') }}</option>
                <option value="one_way">{{ t('shuttle.oneWay') }}</option>
                <option value="round_trip">{{ t('shuttle.roundTrip') }}</option>
                <option value="both">{{ t('shuttle.both') }}</option>
              </select>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- ESTADOS -->
    <div v-if="shuttleStore.isLoading" class="state-container">
      <LoadingBranded :message="t('taxi.loadingTaxis') || 'Cargando viajes...'" icon="airport_shuttle" />
    </div>

    <div v-else-if="shuttleStore.error" class="state-container">
      <span class="material-icons notranslate" translate="no">error_outline</span>
      <p>{{ shuttleStore.error }}</p>
      <button class="retry-btn" @click="shuttleStore.loadShuttles()">
        <span class="material-icons notranslate" translate="no">refresh</span>
        {{ t('common.retry') || 'Reintentar' }}
      </button>
    </div>

    <!-- GRID PREMIUM CON AUTHGUARD -->
    <AuthGuard
      v-else
      :title="t('shuttle.auth.title') || 'Viajes Exclusivos'"
      :message="t('shuttle.auth.message') || 'Regístrate para reservar tus viajes, ver horarios detallados y tarifas de grupo.'"
    >
      <div class="shuttles-grid">
        <div 
          v-for="shuttle in filteredShuttles" 
          :key="shuttle.id" 
          v-memo="[shuttle.id]"
          class="shuttle-card-premium glass-effect"
          @click="verDetalle(shuttle.id, shuttle.company_name || `${shuttle.origin}-${shuttle.destination}`)"
        >
          <div class="card-image-wrap">
            <AppImage 
              :src="shuttle.image_url" 
              type="shuttle"
              imgClass="shuttle-img"
              alt="Shuttle"
            />
            <div class="company-tag" v-if="shuttle.company_name">
              <span class="material-icons notranslate" translate="no">business</span>
              {{ shuttle.company_name }}
            </div>
          </div>

          <div class="card-body-premium">
            <div class="route-header">
              <div class="route-main">
                <span class="location-name">{{ shuttle.origin }}</span>
                <span class="material-icons separator-icon notranslate" translate="no">east</span>
                <span class="location-name">{{ shuttle.destination }}</span>
              </div>
            </div>

            <div class="card-meta">
              <div class="meta-tag">
                <span class="material-icons notranslate" translate="no">directions_bus</span>
                <span>{{ shuttle.vehicle_type }}</span>
              </div>
              <div class="meta-tag" v-if="shuttle.estimated_duration">
                <span class="material-icons notranslate" translate="no">schedule</span>
                <span>{{ shuttle.estimated_duration }}</span>
              </div>
            </div>

            <div class="card-footer-premium">
              <div class="price-container">
                <span class="price-label">{{ t('shuttle.from') || 'Desde' }}</span>
                <span class="price-val">${{ shuttle.price_per_person }}</span>
              </div>
              <button class="view-details-btn">
                <span class="material-icons notranslate" translate="no">chevron_right</span>
              </button>
            </div>
          </div>
        </div>

        <!-- EMPTY STATE -->
        <div v-if="filteredShuttles.length === 0" class="empty-state">
          <span class="material-icons notranslate" translate="no">directions_bus_filled</span>
          <p>{{ t('shuttle.noShuttles') }}</p>
        </div>
      </div>
    </AuthGuard>
  </div>
</template>

<style scoped>
.viajes-turisticos {
  padding-bottom: 2rem;
}

/* FILTROS CONSISTENTES */
.filters-container {
  padding: 0 1rem 1.5rem;
}

.filter-card {
  border-radius: 1rem;
  padding: 0.75rem 1rem;
  border: 1px solid var(--border-color);
  background: var(--card-bg);
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.05);
}

.selectors-side {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 0.5rem;
}

.select-group-premium {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  background: var(--bg-primary);
  border: 1px solid var(--border-color);
  border-radius: 0.75rem;
  padding: 0.5rem 0.75rem;
  transition: all 0.3s ease;
}

.select-group-premium:focus-within {
  border-color: var(--active-color);
}

.group-content {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.group-content label {
  font-size: 0.65rem;
  font-weight: 800;
  text-transform: uppercase;
  color: var(--text-secondary);
  margin-bottom: 0.125rem;
}

.group-content select {
  background: transparent;
  border: none;
  color: var(--text-primary);
  font-weight: 700;
  font-size: 0.9375rem;
  outline: none;
  width: 100%;
}

/* GRID Y CARDS PREMIUM */
.shuttles-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 1.5rem;
  padding: 0 1rem;
}

.shuttle-card-premium {
  border-radius: 1.5rem;
  overflow: hidden;
  border: 1px solid var(--border-color);
  background: var(--card-bg);
  transition: all 0.4s cubic-bezier(0.175, 0.885, 0.32, 1.275);
  cursor: pointer;
  display: flex;
  flex-direction: column;
}

.shuttle-card-premium:hover {
  transform: translateY(-8px);
  border-color: var(--active-color);
  box-shadow: 0 20px 40px rgba(0, 0, 0, 0.2);
}

.card-image-wrap {
  position: relative;
  height: 180px;
  width: 100%;
}

.shuttle-img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.company-tag {
  position: absolute;
  top: 1rem;
  left: 1rem;
  background: rgba(0, 0, 0, 0.7);
  backdrop-filter: blur(8px);
  padding: 0.375rem 0.75rem;
  border-radius: 0.75rem;
  color: #fff;
  font-size: 0.75rem;
  font-weight: 700;
  display: flex;
  align-items: center;
  gap: 0.5rem;
  border: 1px solid rgba(255, 255, 255, 0.2);
}

.card-body-premium {
  padding: 1.25rem;
  display: flex;
  flex-direction: column;
  gap: 1rem;
}

.route-main {
  display: flex;
  align-items: center;
  gap: 0.75rem;
  flex-wrap: wrap;
}

.location-name {
  font-size: 1.125rem;
  font-weight: 800;
  color: var(--text-primary);
}

.separator-icon {
  color: var(--active-color);
  font-size: 1.25rem;
}

.card-meta {
  display: flex;
  gap: 1rem;
}

.meta-tag {
  display: flex;
  align-items: center;
  gap: 0.375rem;
  color: var(--text-secondary);
  font-size: 0.875rem;
  font-weight: 600;
}

.meta-tag .material-icons {
  font-size: 1.125rem;
  color: var(--active-color);
}

.card-footer-premium {
  margin-top: 0.5rem;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-top: 1rem;
  border-top: 1px solid var(--border-color);
}

.price-container {
  display: flex;
  flex-direction: column;
}

.price-label {
  font-size: 0.65rem;
  font-weight: 700;
  text-transform: uppercase;
  color: var(--text-secondary);
}

.price-val {
  font-size: 1.5rem;
  font-weight: 900;
  color: var(--active-color);
}

.view-details-btn {
  width: 44px;
  height: 44px;
  border-radius: 50%;
  background: var(--bg-secondary);
  border: 1px solid var(--border-color);
  color: var(--text-primary);
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.3s ease;
}

.shuttle-card-premium:hover .view-details-btn {
  background: var(--active-color);
  color: #101820;
  border-color: var(--active-color);
  transform: rotate(-45deg);
}

/* ESTADOS */
.state-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 4rem 2rem;
  gap: 1rem;
  text-align: center;
}

.spin {
  animation: spin 1s infinite linear;
  font-size: 3rem;
  color: var(--active-color);
}

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

.retry-btn {
  display: inline-flex;
  align-items: center;
  gap: 0.5rem;
  padding: 0.75rem 1.5rem;
  background: var(--active-color);
  color: #101820;
  border: none;
  border-radius: 99px;
  font-weight: 800;
  cursor: pointer;
  transition: all 0.3s ease;
}

.empty-state {
  grid-column-start: 1;
  grid-column-end: -1;
  text-align: center;
  padding: 4rem 2rem;
  color: var(--text-secondary);
}

.empty-state .material-icons {
  font-size: 4rem;
  margin-bottom: 1rem;
  opacity: 0.5;
}

</style>
