<template>
  <div class="h-full w-full relative">
    <!-- Fullscreen Map -->
    <MapboxGlobe
      ref="mapRef"
      :locations="locations"
      :height="mapHeight"
      :initial-center="[37.64, 55.76]"
      :initial-zoom="2"
      :selected-location-id="selectedLocationId"
      @location-click="handleLocationClick"
    />

    <!-- View toggle button -->
    <div class="absolute top-4 left-4 z-10">
      <NuxtLink
        :to="localePath('/catalog')"
        class="inline-flex items-center gap-2 px-4 py-2 bg-white rounded-lg shadow-lg hover:bg-gray-50 transition-colors"
      >
        <svg class="w-5 h-5 text-gray-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
          <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 6h16M4 12h16M4 18h16"/>
        </svg>
        <span class="font-medium text-gray-700">Список</span>
      </NuxtLink>
    </div>

    <!-- Horizontal scrolling cards (Airbnb-style) -->
    <div class="absolute bottom-0 left-0 right-0 pb-6 pt-4 bg-gradient-to-t from-black/50 to-transparent">
      <div
        ref="cardsContainerRef"
        class="flex gap-4 overflow-x-auto px-4 pb-2 snap-x snap-mandatory scrollbar-hide"
      >
        <div
          v-for="location in locations"
          :key="location.uuid"
          :ref="el => setCardRef(location.uuid, el)"
          class="flex-none w-72 snap-center"
        >
          <div
            class="bg-white rounded-lg shadow-lg p-4 cursor-pointer transition-all duration-200 hover:shadow-xl"
            :class="{
              'ring-2 ring-emerald-500 ring-offset-2': selectedLocationId === location.uuid
            }"
            @click="selectAndFlyTo(location)"
          >
            <div class="flex items-start gap-3">
              <div class="w-10 h-10 bg-emerald-100 rounded-full flex items-center justify-center flex-shrink-0">
                <span class="text-emerald-600 font-semibold">{{ location.name?.charAt(0) }}</span>
              </div>
              <div class="min-w-0 flex-1">
                <h4 class="font-semibold text-gray-900 truncate">{{ location.name }}</h4>
                <p class="text-sm text-gray-500">{{ location.country || 'Страна не указана' }}</p>
                <p v-if="location.distance" class="text-xs text-gray-400 mt-1">{{ location.distance }}</p>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- Loading state -->
    <div
      v-if="isLoading"
      class="absolute inset-0 bg-gray-900/50 flex items-center justify-center"
    >
      <div class="bg-white rounded-lg p-6 flex items-center gap-3">
        <Spinner />
        <span class="text-gray-700">Загружаем локации...</span>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { GetLogisticsNodesDocument } from '~/composables/graphql/public/exchange-generated'

definePageMeta({
  layout: 'map'
})

const localePath = useLocalePath()

interface Location {
  uuid?: string | null
  name?: string | null
  latitude?: number | null
  longitude?: number | null
  country?: string | null
  distance?: string
}

const { execute } = useGraphQL()

const mapRef = ref<{ flyToLocation: (location: Location) => Promise<void> } | null>(null)
const cardsContainerRef = ref<HTMLElement | null>(null)
const cardRefs = ref<Map<string, HTMLElement>>(new Map())

const locations = ref<Location[]>([])
const selectedLocationId = ref<string | null>(null)
const isLoading = ref(true)

// Calculate map height (full viewport minus header)
const mapHeight = ref(0)

const calculateMapHeight = () => {
  // Header is approximately 64px (h-16)
  mapHeight.value = window.innerHeight - 64
}

const setCardRef = (uuid: string | null | undefined, el: any) => {
  if (uuid && el) {
    cardRefs.value.set(uuid, el as HTMLElement)
  }
}

const calculateDistance = (lat: number, lng: number) => {
  const moscowLat = 55.76
  const moscowLng = 37.64
  const distance = Math.sqrt(Math.pow(lat - moscowLat, 2) + Math.pow(lng - moscowLng, 2)) * 111
  return `${Math.round(distance)} км от Москвы`
}

const selectAndFlyTo = async (location: Location) => {
  selectedLocationId.value = location.uuid || null

  if (mapRef.value && location.latitude != null && location.longitude != null) {
    await mapRef.value.flyToLocation(location)
  }
}

const handleLocationClick = (location: Location) => {
  selectedLocationId.value = location.uuid || null

  // Scroll card into view
  if (location.uuid) {
    const cardEl = cardRefs.value.get(location.uuid)
    if (cardEl && cardsContainerRef.value) {
      cardEl.scrollIntoView({
        behavior: 'smooth',
        block: 'nearest',
        inline: 'center'
      })
    }
  }
}

onMounted(async () => {
  calculateMapHeight()
  window.addEventListener('resize', calculateMapHeight)

  try {
    const result = await execute(GetLogisticsNodesDocument, {}, 'public', 'exchange')
    locations.value = (result.getLogisticsNodes || [])
      .filter((loc: any) => loc.latitude != null && loc.longitude != null)
      .map((location: any) => ({
        ...location,
        distance: location.latitude && location.longitude
          ? calculateDistance(location.latitude, location.longitude)
          : undefined
      }))
  } catch (error) {
    console.error('Error loading locations:', error)
  } finally {
    isLoading.value = false
  }
})

onUnmounted(() => {
  window.removeEventListener('resize', calculateMapHeight)
})
</script>

<style scoped>
.scrollbar-hide {
  -ms-overflow-style: none;
  scrollbar-width: none;
}
.scrollbar-hide::-webkit-scrollbar {
  display: none;
}
</style>
