<script setup lang="ts">
import { ref, watch } from 'vue'
import type { BusStop } from '@/types'
import { busStopsService, type BusArrival } from '@/services/busStopsService'
import FavoriteButton from '@/components/FavoriteButton.vue'
import { formatTo12Hour } from '@/utils/timeFormatter'

interface Props {
  busStop: BusStop | null
  isOpen: boolean
}

const props = defineProps<Props>()
const emit = defineEmits(['close', 'navigate'])

const upcomingArrivals = ref<BusArrival[]>([])
const isLoading = ref(false)
const hasGps = ref(false)

// Try to get user GPS position (non-blocking)
async function getUserPosition(): Promise<{ lat: number; lng: number } | null> {
  if (!navigator.geolocation) return null
  return new Promise((resolve) => {
    navigator.geolocation.getCurrentPosition(
      (pos) => resolve({ lat: pos.coords.latitude, lng: pos.coords.longitude }),
      () => resolve(null),  // user denied or error → null (option A: show raw times)
      { timeout: 5000, maximumAge: 60000 }
    )
  })
}

async function loadArrivals() {
  if (!props.busStop) return
  isLoading.value = true
  upcomingArrivals.value = []
  try {
    const pos = await getUserPosition()
    hasGps.value = pos !== null
    upcomingArrivals.value = await busStopsService.getNextBusesForStop(
      props.busStop.id,
      pos?.lat,
      pos?.lng
    )
  } catch (e) {
    console.error('Failed to load arrivals', e)
    upcomingArrivals.value = []
  } finally {
    isLoading.value = false
  }
}

/** Format wait time as human label: "2 min", "1 h 5 min" */
function formatWait(minutes: number): string {
  if (minutes < 1) return 'Llegando'
  if (minutes < 60) return `${Math.round(minutes)} min`
  const h = Math.floor(minutes / 60)
  const m = Math.round(minutes % 60)
  return m > 0 ? `${h}h ${m}min` : `${h}h`
}

function startInternalNavigation() {
  if (props.busStop) {
    emit('navigate', props.busStop)
  }
}

watch(() => props.busStop, async (newStop) => {
  if (newStop && props.isOpen) await loadArrivals()
})

watch(() => props.isOpen, async (isOpen) => {
  if (isOpen && props.busStop) await loadArrivals()
})
</script>

<template>
  <Transition name="modal-fade">
    <div v-if="isOpen" class="modal-overlay" @click="emit('close')">
      <div class="modal-content" @click.stop>
        
        <!-- Header -->
        <div class="modal-header">
          <div v-if="busStop" class="header-info">
            <div class="title-row">
              <h3 class="stop-name">{{ busStop.name }}</h3>
              <FavoriteButton 
                item-type="stop" 
                :item-id="busStop.id" 
                :item-name="busStop.name"
              />
            </div>
            <p v-if="busStop.address" class="stop-address">
              <span class="material-icons text-sm">location_on</span>
              {{ busStop.address }}
            </p>
          </div>
          <button class="close-btn" @click="emit('close')">
             <span class="material-icons">close</span>
          </button>
        </div>

        <!-- Amenities Chips -->
        <div v-if="busStop" class="amenities-container">
           <div v-if="busStop.has_shelter" class="amenity-chip" title="Shelter available">
             <span class="material-icons md-16">roofing</span>
             <span>Cubierta</span>
           </div>
           <div v-if="busStop.has_seating" class="amenity-chip" title="Seating available">
             <span class="material-icons md-16">event_seat</span>
             <span>Asientos</span>
           </div>
           <div v-if="busStop.is_accessible" class="amenity-chip" title="Wheelchair accessible">
             <span class="material-icons md-16">accessible</span>
             <span>Accesible</span>
           </div>
        </div>

        <!-- Body -->
        <div class="modal-body">
          <!-- Section header with GPS status badge -->
          <div class="arrivals-header">
            <h4 class="section-title">Próximos Buses</h4>
            <div v-if="!isLoading" class="gps-badge" :class="hasGps ? 'gps-on' : 'gps-off'">
              <span class="material-icons md-16">{{ hasGps ? 'gps_fixed' : 'gps_off' }}</span>
              <span>{{ hasGps ? 'Tiempo real' : 'Horario' }}</span>
            </div>
          </div>
          
          <div v-if="isLoading" class="loading-state">
            <span class="material-icons spin">refresh</span>
            <p>Obteniendo horarios...</p>
          </div>

          <div v-else-if="upcomingArrivals.length > 0" class="arrivals-list">
            <div 
              v-for="(arrival, index) in upcomingArrivals" 
              :key="index" 
              class="arrival-item"
              :style="{ animationDelay: `${index * 0.07}s` }"
            >
              <div class="route-info">
                <span class="material-icons bus-icon">directions_bus</span>
                <div class="route-texts">
                  <span class="route-name">{{ arrival.routeName }}</span>
                  <span class="departure-hint">Sale: {{ formatTo12Hour(arrival.departureTime) }}</span>
                </div>
              </div>

              <!-- With GPS: show wait minutes + arrival time -->
              <div v-if="arrival.hasGps && arrival.waitMinutes !== null" class="arrival-time-block">
                <span class="wait-badge" :class="arrival.waitMinutes < 10 ? 'urgent' : 'normal'">
                  {{ formatWait(arrival.waitMinutes) }}
                </span>
                <span class="arrival-clock">{{ formatTo12Hour(arrival.arrivalTime) }}</span>
              </div>

              <!-- Without GPS: show raw schedule time -->
              <div v-else class="arrival-time">
                {{ formatTo12Hour(arrival.arrivalTime) }}
              </div>
            </div>
          </div>

          <div v-else class="empty-state">
            <span class="material-icons">schedule</span>
            <p>Sin servicio disponible en este momento</p>
            <span class="empty-hint">Prueba más tarde o revisa el horario completo</span>
          </div>
        </div>

        <!-- Footer / Actions -->
        <div class="modal-footer">
          <button class="action-btn secondary" @click="startInternalNavigation">
            <span class="material-icons md-18">navigation</span>
            Cómo llegar
          </button>
          <button class="action-btn primary" @click="loadArrivals">
            <span class="material-icons md-18">refresh</span>
            Actualizar
          </button>
        </div>

      </div>
    </div>
  </Transition>
</template>

<style scoped>
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: flex-end; /* Bottom sheet style on mobile, centered on desktop ideally */
  z-index: 1000;
}

/* On larger screens, center it */
@media (min-width: 768px) {
  .modal-overlay {
    align-items: center;
  }
}

.modal-content {
  background: var(--card-bg);
  width: 100%;
  max-width: 500px;
  border-radius: 16px 16px 0 0;
  padding: 24px;
  box-shadow: 0 -4px 20px rgba(0,0,0,0.15);
  animation: slide-up 0.3s ease-out;
  color: var(--text-primary);
}

@media (min-width: 768px) {
  .modal-content {
    border-radius: 16px;
    animation: zoom-in 0.2s ease-out;
  }
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 20px;
}

.stop-name {
  font-size: 1.25rem;
  font-weight: 700;
  margin: 0;
  color: var(--text-primary);
}

.stop-address {
  display: flex;
  align-items: center;
  gap: 4px;
  font-size: 0.875rem;
  color: var(--text-secondary);
  margin-top: 4px;
}

.title-row {
  display: flex;
  align-items: center;
  justify-content: space-between;
  width: 100%;
}

.fav-btn {
  background: transparent;
  border: none;
  cursor: pointer;
  padding: 4px;
  display: flex;
  align-items: center;
  color: var(--text-secondary);
  transition: transform 0.2s, color 0.2s;
}

.fav-btn:hover {
  transform: scale(1.2);
}

.fav-btn .material-icons.favorited {
  color: #ff4757;
}

.close-btn {
  background: transparent;
  border: none;
  cursor: pointer;
  color: var(--text-secondary);
  padding: 4px;
}

.arrivals-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}

.section-title {
  font-size: 1rem;
  font-weight: 600;
  margin: 0;
  color: var(--text-primary);
}

.gps-badge {
  display: flex;
  align-items: center;
  gap: 4px;
  font-size: 0.7rem;
  font-weight: 700;
  padding: 3px 8px;
  border-radius: 12px;
  text-transform: uppercase;
  letter-spacing: 0.03em;
}
.gps-badge.gps-on {
  background: rgba(34, 197, 94, 0.12);
  color: #22c55e;
  border: 1px solid rgba(34, 197, 94, 0.3);
}
.gps-badge.gps-off {
  background: var(--bg-secondary);
  color: var(--text-secondary);
  border: 1px solid var(--border-color);
}

.arrivals-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.arrival-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px;
  background-color: var(--bg-secondary);
  border-radius: 8px;
}

.route-info {
  display: flex;
  align-items: center;
  gap: 8px;
  flex: 1;
  min-width: 0;
}

.route-texts {
  display: flex;
  flex-direction: column;
  gap: 1px;
  min-width: 0;
}

.bus-icon {
  color: var(--header-bg);
  flex-shrink: 0;
}

.route-name {
  font-weight: 600;
  font-size: 0.875rem;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.departure-hint {
  font-size: 0.72rem;
  color: var(--text-secondary);
}

/* Raw time (no GPS) */
.arrival-time {
  font-weight: 700;
  font-size: 0.95rem;
  color: var(--active-color, green);
  white-space: nowrap;
  flex-shrink: 0;
}

/* GPS mode: wait badge + clock */
.arrival-time-block {
  display: flex;
  flex-direction: column;
  align-items: flex-end;
  gap: 2px;
  flex-shrink: 0;
}

.wait-badge {
  font-size: 0.8rem;
  font-weight: 800;
  padding: 2px 8px;
  border-radius: 10px;
  white-space: nowrap;
}
.wait-badge.urgent {
  background: rgba(239, 68, 68, 0.12);
  color: #ef4444;
  border: 1px solid rgba(239, 68, 68, 0.3);
}
.wait-badge.normal {
  background: rgba(34, 197, 94, 0.12);
  color: #22c55e;
  border: 1px solid rgba(34, 197, 94, 0.25);
}

.arrival-clock {
  font-size: 0.72rem;
  color: var(--text-secondary);
}

/* Amenities Styles */
.amenities-container {
  display: flex;
  gap: 8px;
  margin-bottom: 20px;
  flex-wrap: wrap;
}

.amenity-chip {
  display: flex;
  align-items: center;
  gap: 4px;
  background-color: var(--bg-secondary);
  padding: 4px 10px;
  border-radius: 16px;
  font-size: 0.75rem;
  font-weight: 500;
  color: var(--text-secondary);
  border: 1px solid var(--border-color);
}

.md-16 { font-size: 16px; }
.md-18 { font-size: 18px; }

/* Modal Footer */
.modal-footer {
  margin-top: 24px;
  display: flex;
  justify-content: space-between; /* Spread buttons */
  gap: 12px;
}

.action-btn {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 10px 20px;
  border-radius: 8px;
  font-weight: 600;
  cursor: pointer;
  border: none;
  font-size: 0.9rem;
  transition: all 0.2s ease;
}

.action-btn.primary {
  background-color: var(--text-primary);
  color: var(--bg-primary);
  flex: 1; /* Take remaining space */
  justify-content: center;
}

.action-btn.secondary {
  background-color: transparent;
  color: var(--text-primary);
  border: 1px solid var(--border-color);
}

.action-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(0,0,0,0.1);
}

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

/* Animations */
.arrival-item {
  animation: fade-in-slide 0.4s ease-out forwards;
  opacity: 0; 
  transform: translateY(10px);
}

@keyframes fade-in-slide {
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

@keyframes slide-up {
  from { transform: translateY(100%); }
  to { transform: translateY(0); }
}

@keyframes zoom-in {
  from { opacity: 0; transform: scale(0.95); }
  to { opacity: 1; transform: scale(1); }
}

.modal-fade-enter-active,
.modal-fade-leave-active {
  transition: opacity 0.3s ease;
}

.modal-fade-enter-from,
.modal-fade-leave-to {
  opacity: 0;
}

.loading-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 20px;
  color: var(--text-secondary);
}

.spin {
  animation: spin 1s linear infinite;
  margin-bottom: 8px;
}

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

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 8px;
  padding: 24px 16px;
  text-align: center;
  color: var(--text-secondary);
}

.empty-state .material-icons {
  font-size: 2.5rem;
  opacity: 0.4;
}

.empty-state p {
  margin: 0;
  font-size: 0.9rem;
  font-weight: 500;
  color: var(--text-primary);
}

.empty-hint {
  font-size: 0.78rem;
  color: var(--text-secondary);
  opacity: 0.75;
}

</style>
