<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { supabase } from '@/supabase'
import type { Shuttle } from '@/types'
import { getImageUrl } from '@/utils/imageUrl'
import { analyticsService } from '@/services/analyticsService'
import { useI18n } from 'vue-i18n'
import LoadingBranded from '@/components/common/LoadingBranded.vue'
import FavoriteButton from '@/components/FavoriteButton.vue'

const route = useRoute()
const router = useRouter()
const { t } = useI18n()
const shuttle = ref<Shuttle | null>(null)
const cargando = ref(true)
const error = ref<string | null>(null)

onMounted(async () => {
  try {
    cargando.value = true
    const shuttleId = route.params.id as string

    // In a real app we might just get from the store, but directly from Supabase is safe to ensure it always works with Deep Links!
    const { data, error: sbError } = await supabase
      .from('shuttles')
      .select('*')
      .eq('id', shuttleId)
      .single()

    if (sbError) throw sbError
    shuttle.value = data
  } catch (e: any) {
    error.value = t('shuttle.errorLoading')
    console.error('SIBU | Error cargando shuttle:', e)
  } finally {
    cargando.value = false
  }
})

const parsePrice = (priceVal?: number | string | null): string => {
  if (!priceVal) return '0.00';
  const num = typeof priceVal === 'string' ? parseFloat(priceVal) : priceVal;
  return Number.isNaN(num) ? '0.00' : num.toFixed(2);
};

const volver = () => {
  // Leer la ruta padre desde el meta de la ruta actual
  const rutaPadre = route.meta.padre as string | undefined

  if (rutaPadre) {
    router.push({ name: rutaPadre })
  } else {
    // Fallback seguro
    router.push('/transporte/viajes-turisticos')
  }
}

const getTripTypeLabel = (type: string) => {
  if (type === 'one_way') return t('shuttle.oneWay')
  if (type === 'round_trip') return t('shuttle.roundTrip')
  if (type === 'both') return t('shuttle.both')
  return type
}
</script>

<template>
  <div class="shuttle-detalle-container bg-[var(--bg-primary)] pb-24 min-h-screen relative">
    <!-- Header con botón volver (Solid background to avoid overlap on scroll) -->
    <div class="sticky top-0 z-50 bg-[var(--bg-primary)] border-b border-border flex items-center gap-3 px-4 py-3 shadow-md" style="padding-top: max(env(safe-area-inset-top), 12px);">
      <button @click="volver" class="p-2 rounded-full hover:bg-[var(--hover-bg)] flex items-center justify-center transition">
        <span class="material-icons text-[var(--text-primary)]">arrow_back</span>
      </button>
      <h1 class="font-bold text-[var(--text-primary)] text-lg truncate flex-1">
        {{ shuttle?.company_name || t('shuttle.detailTitle') }}
      </h1>
      <FavoriteButton
        v-if="shuttle"
        item-type="shuttle"
        :item-id="shuttle.id"
        :item-name="shuttle.company_name || shuttle.origin + ' - ' + shuttle.destination"
        :item-image="shuttle.image_url || undefined"
      />
    </div>

    <!-- Loading -->
    <div v-if="cargando" class="flex flex-col justify-center items-center h-64 gap-3 w-full">
       <LoadingBranded :message="t('common.loading') || 'Cargando detalle...'" icon="airport_shuttle" />
    </div>

    <!-- Error -->
    <div v-else-if="error" class="flex flex-col items-center justify-center h-64 px-6 text-center">
      <span class="material-icons text-red-500 text-5xl mb-3">error_outline</span>
      <p class="text-red-500 font-medium">{{ error }}</p>
      <button @click="volver" class="mt-6 px-6 py-2 bg-text-primary text-surface font-bold rounded-full shadow hover:opacity-90 transition">
        {{ t('common.back') }}
      </button>
    </div>

    <!-- Contenido completo -->
    <div v-else-if="shuttle" class="px-4 py-4 space-y-4 max-w-lg mx-auto animate-fade-in">
      <!-- Imagen -->
      <div v-if="shuttle.image_url" class="relative w-full h-56 md:h-64 rounded-2xl overflow-hidden shadow-sm">
        <img 
          :src="getImageUrl(shuttle.image_url, 'shuttle')"
          :alt="shuttle.company_name"
          class="w-full h-full object-cover" 
          @error="(e) => (e.target as HTMLImageElement).src = getImageUrl(null, 'shuttle')"
        />
        <div class="absolute bottom-3 left-3 bg-[var(--bg-primary)]/90 backdrop-blur-sm px-3 py-1 rounded-full text-sm font-bold shadow-sm flex items-center gap-1">
           <span class="material-icons text-sm" style="color: var(--active-color)">directions_bus</span>
           {{ shuttle.vehicle_type }}
        </div>
      </div>

      <!-- Rutas Origen - Destino prominente -->
      <div class="bg-[var(--bg-secondary)] rounded-2xl p-5 shadow-sm space-y-3 border border-border">
         <div class="flex items-center justify-between">
           <div class="flex flex-col flex-1">
              <span class="text-xs text-[var(--text-secondary)] font-semibold mb-1 uppercase tracking-wider">{{ t('shuttle.origin') }}</span>
              <span class="font-bold text-[var(--text-primary)] text-lg leading-tight break-words">
                {{ shuttle.origin }}
              </span>
           </div>
           
           <div class="flex flex-col items-center px-4 shrink-0">
             <span class="text-xs text-[var(--text-secondary)] font-bold mb-1">{{ shuttle.estimated_duration }}</span>
             <div class="w-16 border-t-2 border-dashed border-border relative my-1">
                 <span class="material-icons absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 text-[var(--text-secondary)] bg-[var(--bg-secondary)] px-1 text-sm">east</span>
             </div>
           </div>
           
           <div class="flex flex-col flex-1 text-right">
              <span class="text-xs text-[var(--text-secondary)] font-semibold mb-1 uppercase tracking-wider">{{ t('shuttle.destination') }}</span>
              <span class="font-bold text-[var(--text-primary)] text-lg leading-tight break-words">
                {{ shuttle.destination }}
              </span>
           </div>
         </div>
      </div>

      <!-- Info principal -->
      <div class="bg-[var(--bg-secondary)] rounded-2xl p-5 shadow-sm space-y-4 border border-border">
        <div>
          <h2 class="text-xl font-bold text-[var(--text-primary)]">{{ shuttle.company_name }}</h2>
          <p class="text-[var(--text-secondary)] text-sm mt-1 leading-relaxed" v-if="shuttle.description" style="white-space: pre-wrap;">{{ shuttle.description }}</p>
        </div>
 
        <div class="grid grid-cols-2 gap-4 pt-4 border-t border-border">
          <div class="flex flex-col gap-1">
            <span class="text-xs text-[var(--text-secondary)] uppercase tracking-wider font-semibold flex items-center gap-1"><span class="material-icons text-sm">schedule</span> {{ t('shuttle.departureTimes') }}</span>
            <span class="font-semibold text-[var(--text-primary)] bg-[var(--bg-primary)] p-2 rounded-lg text-sm text-center border border-border">
              {{ shuttle.departure_times }}
            </span>
          </div>
          <div class="flex flex-col gap-1">
            <span class="text-xs text-[var(--text-secondary)] uppercase tracking-wider font-semibold flex items-center gap-1"><span class="material-icons text-sm">swap_horiz</span> {{ t('shuttle.tripType') }}</span>
            <span class="font-semibold text-[var(--text-primary)] bg-[var(--bg-primary)] p-2 rounded-lg text-sm text-center border border-border">
              {{ getTripTypeLabel(shuttle.trip_type) }}
            </span>
          </div>
          <div class="flex flex-col gap-1" v-if="shuttle.english_speaking">
            <span class="text-xs text-[var(--text-secondary)] uppercase tracking-wider font-semibold flex items-center gap-1"><span class="material-icons text-sm">g_translate</span> {{ t('shuttle.languages') }}</span>
            <span class="font-semibold text-[var(--text-primary)] bg-[var(--bg-primary)] p-2 rounded-lg text-sm text-center border border-border">
              Español · English
            </span>
          </div>
        </div>
      </div>

      <!-- Precio -->
      <div class="rounded-2xl p-6 shadow-sm flex items-center justify-between" style="background-color: var(--active-color); color: #101820;">
        <div class="text-left">
           <p class="text-sm font-semibold opacity-90 mb-1">{{ t('shuttle.pricePerPerson') }}</p>
           <div class="flex items-baseline gap-1">
             <span class="text-lg font-bold opacity-80">$</span>
             <span class="text-4xl font-black tracking-tight">{{ parsePrice(shuttle.price_per_person) }}</span>
           </div>
        </div>
        <div class="p-3 rounded-xl bg-black/10 backdrop-blur-sm" v-if="shuttle.price_private_trip">
           <span class="text-xs font-bold uppercase tracking-wider opacity-90 block mb-1">{{ t('shuttle.private') }}</span>
           <span class="font-black text-lg">${{ parsePrice(shuttle.price_private_trip) }}</span>
        </div>
      </div>

      <!-- Contacto -->
      <div class="bg-[var(--bg-secondary)] rounded-2xl p-5 shadow-sm space-y-4 border border-border mb-8">
        <div>
          <h3 class="font-bold text-[var(--text-primary)] text-lg">{{ t('shuttle.bookingInfo') }}</h3>
          <p class="text-sm text-[var(--text-secondary)] mt-1">{{ t('shuttle.contactOperator') }}</p>
        </div>
        
        <div class="flex flex-col gap-3">
          <a v-if="shuttle.contact_whatsapp"
            :href="`https://wa.me/${shuttle.contact_whatsapp.replace(/\+/g, '')}?text=Hola,%20me%20gustaría%20información%20sobre%20el%20shuttle%20de%20${shuttle.origin}%20a%20${shuttle.destination}`"
            target="_blank"
            class="flex justify-center items-center gap-2 p-3.5 bg-[#25D366] text-white rounded-xl font-bold hover:opacity-90 transition active:scale-95"
            @click="analyticsService.logEvent({ event_name: 'shuttle_contact', entity_type: 'shuttle', entity_id: shuttle.id, entity_name: shuttle.company_name || 'shuttle', properties: { action: 'whatsapp' } })"
          >
            <span class="material-icons">chat</span>
            {{ t('shuttle.bookWhatsapp') }}
          </a>
          
          <a v-if="shuttle.phone_number"
            :href="`tel:${shuttle.phone_number}`"
            class="flex justify-center items-center gap-2 p-3.5 bg-[var(--bg-primary)] text-[var(--text-primary)] rounded-xl font-bold hover:bg-[var(--hover-bg)] transition active:scale-95 border border-border"
            @click="analyticsService.logEvent({ event_name: 'shuttle_contact', entity_type: 'shuttle', entity_id: shuttle.id, entity_name: shuttle.company_name || 'shuttle', properties: { action: 'call' } })"
          >
            <span class="material-icons">phone_in_talk</span>
            {{ t('shuttle.callOperator') }}
          </a>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
.animate-fade-in {
  animation: fadeIn 0.3s ease-out forwards;
}

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

.spin {
  animation: spin 1s infinite linear;
}

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