<template>
  <div class="flex flex-col flex-1 min-h-0">
    <!-- Loading state -->
    <div v-if="loading" class="flex-1 flex items-center justify-center">
      <Card padding="lg">
        <Stack align="center" justify="center" gap="3">
          <Spinner />
          <Text tone="muted">{{ $t('catalogLanding.states.loading') }}</Text>
        </Stack>
      </Card>
    </div>

    <!-- Content -->
    <template v-else>
      <!-- With Map: Split Layout -->
      <template v-if="withMap">
        <!-- Desktop: side-by-side -->
        <div class="hidden lg:flex flex-1 gap-4 min-h-0 py-4">
          <!-- Left: List (scrollable) -->
          <div class="w-2/5 overflow-y-auto pr-2">
            <Stack gap="4">
              <slot name="filters" />

              <Stack gap="3">
                <div
                  v-for="item in items"
                  :key="item.uuid"
                  :class="{ 'ring-2 ring-primary rounded-lg': item.uuid === selectedId }"
                  @click="onItemClick(item)"
                >
                  <slot name="card" :item="item" />
                </div>
              </Stack>

              <slot name="pagination" />

              <Stack v-if="items.length === 0" align="center" gap="2">
                <slot name="empty">
                  <Text tone="muted">{{ $t('common.values.not_available') }}</Text>
                </slot>
              </Stack>
            </Stack>
          </div>

          <!-- Right: Map -->
          <div class="w-3/5 rounded-lg overflow-hidden">
            <ClientOnly>
              <CatalogMap
                ref="mapRef"
                :map-id="mapId"
                :items="itemsWithCoords"
                :point-color="pointColor"
                @select-item="onMapSelect"
              />
            </ClientOnly>
          </div>
        </div>

        <!-- Mobile: toggle between list and map -->
        <div class="lg:hidden flex-1 flex flex-col min-h-0">
          <div class="flex-1 overflow-y-auto py-4" v-show="mobileView === 'list'">
            <Stack gap="4">
              <slot name="filters" />

              <Stack gap="3">
                <div
                  v-for="item in items"
                  :key="item.uuid"
                  :class="{ 'ring-2 ring-primary rounded-lg': item.uuid === selectedId }"
                  @click="onItemClick(item)"
                >
                  <slot name="card" :item="item" />
                </div>
              </Stack>

              <slot name="pagination" />

              <Stack v-if="items.length === 0" align="center" gap="2">
                <slot name="empty">
                  <Text tone="muted">{{ $t('common.values.not_available') }}</Text>
                </slot>
              </Stack>
            </Stack>
          </div>

          <div class="flex-1" v-show="mobileView === 'map'">
            <ClientOnly>
              <CatalogMap
                ref="mobileMapRef"
                :map-id="`${mapId}-mobile`"
                :items="itemsWithCoords"
                :point-color="pointColor"
                @select-item="onMapSelect"
              />
            </ClientOnly>
          </div>

          <!-- Mobile toggle -->
          <div class="fixed bottom-4 left-1/2 -translate-x-1/2 z-30">
            <div class="btn-group shadow-lg">
              <button
                class="btn btn-sm"
                :class="{ 'btn-active': mobileView === 'list' }"
                @click="mobileView = 'list'"
              >
                {{ $t('common.list') }}
              </button>
              <button
                class="btn btn-sm"
                :class="{ 'btn-active': mobileView === 'map' }"
                @click="mobileView = 'map'"
              >
                {{ $t('common.map') }}
              </button>
            </div>
          </div>
        </div>
      </template>

      <!-- Without Map: Simple List -->
      <div v-else class="flex-1 overflow-y-auto py-4">
        <Stack gap="4">
          <slot name="filters" />

          <Stack gap="3">
            <div
              v-for="item in items"
              :key="item.uuid"
              @click="onItemClick(item)"
            >
              <slot name="card" :item="item" />
            </div>
          </Stack>

          <slot name="pagination" />

          <Stack v-if="items.length === 0" align="center" gap="2">
            <slot name="empty">
              <Text tone="muted">{{ $t('common.values.not_available') }}</Text>
            </slot>
          </Stack>
        </Stack>
      </div>
    </template>
  </div>
</template>

<script setup lang="ts">
interface MapItem {
  uuid: string
  latitude?: number | null
  longitude?: number | null
  name?: string
  country?: string
  [key: string]: any
}

const props = withDefaults(defineProps<{
  items: MapItem[]
  loading?: boolean
  withMap?: boolean
  mapId?: string
  pointColor?: string
  selectedId?: string
}>(), {
  loading: false,
  withMap: true,
  mapId: 'catalog-map',
  pointColor: '#3b82f6'
})

const emit = defineEmits<{
  'select': [item: MapItem]
  'update:selectedId': [uuid: string]
}>()

// Filter items with valid coordinates for map
const itemsWithCoords = computed(() =>
  props.items.filter(item =>
    item.latitude != null &&
    item.longitude != null &&
    !isNaN(Number(item.latitude)) &&
    !isNaN(Number(item.longitude))
  ).map(item => ({
    uuid: item.uuid,
    name: item.name || '',
    latitude: Number(item.latitude),
    longitude: Number(item.longitude),
    country: item.country
  }))
)

// Mobile view toggle
const mobileView = ref<'list' | 'map'>('list')

// Map refs
const mapRef = ref<{ flyTo: (lat: number, lng: number, zoom?: number) => void } | null>(null)
const mobileMapRef = ref<{ flyTo: (lat: number, lng: number, zoom?: number) => void } | null>(null)

// Handle item click from list
const onItemClick = (item: MapItem) => {
  emit('select', item)
  emit('update:selectedId', item.uuid)

  // Fly to item on map
  if (props.withMap && item.latitude && item.longitude) {
    mapRef.value?.flyTo(Number(item.latitude), Number(item.longitude), 8)
    mobileMapRef.value?.flyTo(Number(item.latitude), Number(item.longitude), 8)
  }
}

// Handle selection from map
const onMapSelect = (uuid: string) => {
  const item = props.items.find(i => i.uuid === uuid)
  if (item) {
    emit('select', item)
    emit('update:selectedId', uuid)
  }
}

// Watch selectedId and fly to it
watch(() => props.selectedId, (uuid) => {
  if (uuid && props.withMap) {
    const item = itemsWithCoords.value.find(i => i.uuid === uuid)
    if (item) {
      mapRef.value?.flyTo(item.latitude, item.longitude, 8)
      mobileMapRef.value?.flyTo(item.latitude, item.longitude, 8)
    }
  }
})

// Expose flyTo for external use
const flyTo = (lat: number, lng: number, zoom = 8) => {
  mapRef.value?.flyTo(lat, lng, zoom)
  mobileMapRef.value?.flyTo(lat, lng, zoom)
}

defineExpose({ flyTo })
</script>
