<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 ShuttleSkeletonCard from '@/components/transporte/ShuttleSkeletonCard.vue'
import TransportFilterSelect from '@/components/transporte/TransportFilterSelect.vue'

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

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

const categoryOptions = computed(() => [
  { value: 'all', label: t('shuttle.allAreas') || 'Todas', icon: 'grid_view' },
  { value: 'local', label: t('shuttle.local') || 'Local', icon: 'place' },
  { value: 'interprovincial', label: t('shuttle.interprovincial') || 'Interprovincial', icon: 'route' },
])

const typeOptions = computed(() => [
  { value: 'all', label: t('common.all'), icon: 'swap_horiz' },
  { value: 'one_way', label: t('shuttle.oneWay'), icon: 'arrow_forward' },
  { value: 'round_trip', label: t('shuttle.roundTrip'), icon: 'sync_alt' },
  { value: 'both', label: t('shuttle.both'), icon: 'directions' },
])

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 hasActiveFilters = computed(() =>
  shuttleCategoryFilter.value !== 'all' || shuttleTypeFilter.value !== 'all'
)

function clearFilters() {
  shuttleCategoryFilter.value = 'all'
  shuttleTypeFilter.value = 'all'
}

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() {
  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">
    <!-- FILTERS -->
    <div class="filters-wrap">
      <TransportFilterSelect
        v-model="shuttleCategoryFilter"
        :options="categoryOptions"
      />
      <TransportFilterSelect
        v-model="shuttleTypeFilter"
        :options="typeOptions"
      />
    </div>

    <!-- LOADING SKELETONS -->
    <div v-if="shuttleStore.isLoading" class="shuttles-grid" aria-busy="true" aria-label="Cargando viajes...">
      <ShuttleSkeletonCard v-for="n in 4" :key="n" />
    </div>

    <!-- ERROR -->
    <div v-else-if="shuttleStore.error" class="state-container" role="alert">
      <span class="material-icons notranslate state-icon state-icon--error" translate="no" aria-hidden="true">error_outline</span>
      <p>{{ shuttleStore.error }}</p>
      <button class="retry-btn" @click="shuttleStore.loadShuttles()">
        <span class="material-icons notranslate" translate="no" aria-hidden="true">refresh</span>
        {{ t('common.retry') }}
      </button>
    </div>

    <!-- GRID -->
    <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" role="list" :aria-label="'Viajes disponibles'">
        <article
          v-for="shuttle in filteredShuttles"
          :key="shuttle.id"
          v-memo="[shuttle.id]"
          class="shuttle-card glass-effect"
          role="listitem"
          :aria-label="`${shuttle.origin} a ${shuttle.destination}${shuttle.company_name ? ', ' + shuttle.company_name : ''}`"
          @click="verDetalle(shuttle.id, shuttle.company_name || `${shuttle.origin}-${shuttle.destination}`)"
          @keydown.enter="verDetalle(shuttle.id, shuttle.company_name || `${shuttle.origin}-${shuttle.destination}`)"
          tabindex="0"
        >
          <!-- Image — desktop full, mobile strip -->
          <div class="card-image-wrap" aria-hidden="true">
            <AppImage
              :src="shuttle.image_url"
              type="shuttle"
              imgClass="shuttle-img"
              alt=""
            />
            <div class="company-tag" v-if="shuttle.company_name">
              <span class="material-icons notranslate" translate="no" aria-hidden="true">business</span>
              {{ shuttle.company_name }}
            </div>
          </div>

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

            <div class="card-meta">
              <div class="meta-tag">
                <span class="material-icons notranslate" translate="no" aria-hidden="true">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" aria-hidden="true">schedule</span>
                <span>{{ shuttle.estimated_duration }}</span>
              </div>
            </div>

            <div class="card-footer">
              <div class="price-container">
                <span class="price-label">{{ t('shuttle.from') || 'Desde' }}</span>
                <span class="price-val" :aria-label="`Precio desde $${shuttle.price_per_person}`">${{ shuttle.price_per_person }}</span>
              </div>
              <div class="view-details-btn" aria-hidden="true">
                <span class="material-icons notranslate" translate="no">chevron_right</span>
              </div>
            </div>
          </div>
        </article>

        <!-- EMPTY STATE -->
        <div v-if="filteredShuttles.length === 0" class="empty-state" role="status">
          <span class="material-icons notranslate empty-icon" translate="no" aria-hidden="true">directions_bus_filled</span>
          <p class="empty-title">{{ t('shuttle.noShuttles') }}</p>
          <button v-if="hasActiveFilters" class="clear-filters-btn" @click="clearFilters">
            <span class="material-icons notranslate" translate="no" aria-hidden="true">filter_alt_off</span>
            {{ t('common.clear') }}
          </button>
        </div>
      </div>
    </AuthGuard>
  </div>
</template>

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

/* FILTERS */
.filters-wrap {
  padding: 0 1rem 0.75rem;
  display: flex;
  flex-direction: row;
  gap: 0.5rem;
  flex-wrap: wrap;
}

/* GRID — single column on mobile, 2-col on tablet, 3-col on desktop */
.shuttles-grid {
  display: grid;
  grid-template-columns: 1fr;
  gap: 1rem;
  padding: 0.5rem 1rem 1.5rem;
}

@media (min-width: 640px) {
  .shuttles-grid {
    grid-template-columns: repeat(2, 1fr);
    gap: 1.25rem;
  }
}

@media (min-width: 1024px) {
  .shuttles-grid {
    grid-template-columns: repeat(3, 1fr);
    gap: 1.5rem;
  }
}

/* CARD — horizontal on mobile, vertical on tablet+ */
.shuttle-card {
  border-radius: 1.25rem;
  overflow: hidden;
  border: 1px solid var(--border-color);
  background: var(--card-bg);
  transition: transform 0.25s ease, box-shadow 0.25s ease, border-color 0.25s ease;
  cursor: pointer;
  /* Horizontal layout on mobile */
  display: flex;
  flex-direction: row;
}

.shuttle-card:focus-visible {
  outline: 2px solid var(--active-color);
  outline-offset: 2px;
}

@media (min-width: 480px) {
  /* Vertical card layout on larger screens */
  .shuttle-card {
    flex-direction: column;
  }
}

@media (hover: hover) {
  .shuttle-card:hover {
    transform: translateY(-5px);
    border-color: var(--active-color);
    box-shadow: 0 16px 36px rgba(0, 0, 0, 0.18);
  }

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

/* Image: small strip on mobile, full-width on larger */
.card-image-wrap {
  position: relative;
  width: 100px;
  min-height: 120px;
  flex-shrink: 0;
}

@media (min-width: 480px) {
  .card-image-wrap {
    width: 100%;
    min-height: unset;
    height: 170px;
  }
}

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

.company-tag {
  position: absolute;
  top: 0.75rem;
  left: 0.75rem;
  background: rgba(0, 0, 0, 0.7);
  backdrop-filter: blur(8px);
  padding: 0.25rem 0.625rem;
  border-radius: 0.625rem;
  color: #fff;
  font-size: 0.7rem;
  font-weight: 700;
  display: flex;
  align-items: center;
  gap: 0.375rem;
  border: 1px solid rgba(255, 255, 255, 0.2);
  /* Hide on mobile to save space */
  display: none;
}

@media (min-width: 480px) {
  .company-tag {
    display: flex;
  }
}

.card-body {
  padding: 0.875rem;
  display: flex;
  flex-direction: column;
  gap: 0.625rem;
  flex: 1;
  min-width: 0;
}

@media (min-width: 480px) {
  .card-body {
    padding: 1.125rem;
    gap: 0.875rem;
  }
}

.route-header {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  flex-wrap: wrap;
}

.location-name {
  font-size: 0.9375rem;
  font-weight: 800;
  color: var(--text-primary);
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  max-width: 80px;
}

@media (min-width: 480px) {
  .location-name {
    font-size: 1.0625rem;
    max-width: none;
  }
}

.separator-icon {
  color: var(--active-color);
  font-size: 1.125rem;
  flex-shrink: 0;
}

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

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

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

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

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

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

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

@media (min-width: 480px) {
  .price-val {
    font-size: 1.5rem;
  }
}

.view-details-btn {
  width: 40px;
  height: 40px;
  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.25s ease;
  flex-shrink: 0;
}

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

.state-icon {
  font-size: 3rem;
}

.state-icon--error {
  color: #ef4444;
}

.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: transform 0.15s ease;
  min-height: 44px;
}

.retry-btn:active {
  transform: scale(0.97);
}

.empty-state {
  grid-column: 1 / -1;
  text-align: center;
  padding: 3.5rem 2rem;
  color: var(--text-secondary);
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 1rem;
}

.empty-icon {
  font-size: 3.5rem;
  opacity: 0.4;
}

.empty-title {
  font-size: 1rem;
  font-weight: 600;
  margin: 0;
}

.clear-filters-btn {
  display: inline-flex;
  align-items: center;
  gap: 0.5rem;
  padding: 0.625rem 1.25rem;
  background: var(--bg-secondary);
  border: 1.5px solid var(--border-color);
  border-radius: 99px;
  font-weight: 700;
  font-size: 0.875rem;
  color: var(--text-primary);
  cursor: pointer;
  transition: border-color 0.18s ease;
  min-height: 44px;
}

.clear-filters-btn:hover {
  border-color: var(--active-color);
}

@media (prefers-reduced-motion: reduce) {
  .shuttle-card,
  .view-details-btn,
  .retry-btn,
  .clear-filters-btn {
    transition: none;
  }
}
</style>
