<template>
  <div class="route-map">
    <ClientOnly>
      <LMap
        :style="`height: ${height}px; width: 100%;`"
        :zoom="3"
        :center="mapCenter"
        :use-global-leaflet="false"
        class="rounded-lg border border-gray-200"
        @ready="onMapReady"
      >
        <LTileLayer 
          url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png" 
          attribution="&copy; <a href='https://www.openstreetmap.org/'>OpenStreetMap</a> contributors" 
        />
        
        <!-- Маркеры точек маршрута -->
        <LMarker 
          v-for="(point, index) in routePoints" 
          :key="point.id"
          :lat-lng="[point.lat, point.lng]"
        >
          <LPopup>
            <div class="p-2">
              <h4 class="font-semibold text-sm">{{ point.name }}</h4>
              <div v-if="point.companies?.length" class="mt-2">
                <p class="text-xs text-gray-700">Компании:</p>
                <div v-for="company in point.companies" :key="company.uuid" class="text-xs">
                  {{ company.name }}
                </div>
              </div>
            </div>
          </LPopup>
        </LMarker>
        
        <!-- Линии маршрута -->
        <LPolyline 
          v-if="routeCoordinates.length > 1"
          :lat-lngs="routeCoordinates"
          :weight="3"
          color="#3b82f6"
          :opacity="0.7"
        />
      </LMap>
      
      <template #fallback>
        <div class="h-96 w-full bg-gray-100 rounded-lg flex items-center justify-center">
          <p class="text-gray-500">Загрузка карты...</p>
        </div>
      </template>
    </ClientOnly>
  </div>
</template>

<script setup>
const props = defineProps({
  stages: {
    type: Array,
    default: () => []
  },
  height: {
    type: Number,
    default: 400
  }
})

const routePoints = computed(() => {
  const points = []
  
  props.stages.forEach((stage) => {
    if (stage.stageType === 'transport') {
      // Исходная точка с реальными координатами
      if (stage.sourceLatitude && stage.sourceLongitude) {
        const existingPoint = points.find(p => p.lat === stage.sourceLatitude && p.lng === stage.sourceLongitude)
        if (!existingPoint) {
          points.push({
            id: `source-${stage.uuid}`,
            name: stage.sourceLocationName || 'Точка отправления',
            lat: stage.sourceLatitude,
            lng: stage.sourceLongitude,
            stage: stage,
            companies: getStageCompanies(stage)
          })
        }
      }
      
      // Целевая точка с реальными координатами
      if (stage.destinationLatitude && stage.destinationLongitude) {
        const existingPoint = points.find(p => p.lat === stage.destinationLatitude && p.lng === stage.destinationLongitude)
        if (!existingPoint) {
          points.push({
            id: `dest-${stage.uuid}`,
            name: stage.destinationLocationName || 'Точка назначения',
            lat: stage.destinationLatitude,
            lng: stage.destinationLongitude,
            stage: stage,
            companies: getStageCompanies(stage)
          })
        }
      }
    } else {
      // Service этап с реальными координатами
      if (stage.locationLatitude && stage.locationLongitude) {
        const existingPoint = points.find(p => p.lat === stage.locationLatitude && p.lng === stage.locationLongitude)
        if (!existingPoint) {
          points.push({
            id: `service-${stage.uuid}`,
            name: stage.locationName || 'Точка услуги',
            lat: stage.locationLatitude,
            lng: stage.locationLongitude,
            stage: stage,
            companies: getStageCompanies(stage)
          })
        }
      }
    }
  })
  
  return points
})

// Вычисляем центр карты на основе координат точек
const mapCenter = computed(() => {
  if (!routePoints.value.length) return [0, 0]
  
  const lats = routePoints.value.map(p => p.lat).filter(Boolean)
  const lngs = routePoints.value.map(p => p.lng).filter(Boolean)
  
  if (!lats.length || !lngs.length) return [0, 0]
  
  const avgLat = lats.reduce((a, b) => a + b, 0) / lats.length
  const avgLng = lngs.reduce((a, b) => a + b, 0) / lngs.length
  
  return [avgLat, avgLng]
})

// Исправляем иконки маркеров для локального использования  
const onMapReady = (map) => {
  // Импортируем Leaflet напрямую для настройки иконок
  if (process.client) {
    import('leaflet').then((L) => {
      delete L.default.Icon.Default.prototype._getIconUrl
      L.default.Icon.Default.mergeOptions({
        iconUrl: '/leaflet/marker-icon.png',
        iconRetinaUrl: '/leaflet/marker-icon-2x.png', 
        shadowUrl: '/leaflet/marker-shadow.png',
        iconSize: [25, 41],
        iconAnchor: [12, 41],
        popupAnchor: [1, -34],
        shadowSize: [41, 41]
      })
      
      // Убираем украинский флаг из attribution
      if (map && map.attributionControl) {
        map.attributionControl.setPrefix(false)
      }
    })
  }
}

const routeCoordinates = computed(() => {
  return routePoints.value.map(point => [point.lat, point.lng])
})

const getStageCompanies = (stage) => {
  const companies = []
  
  if (stage.selectedCompany) {
    companies.push(stage.selectedCompany)
  }
  
  const uniqueCompanies = new Set()
  stage.trips?.forEach(trip => {
    if (trip.company && !uniqueCompanies.has(trip.company.uuid)) {
      uniqueCompanies.add(trip.company.uuid)
      companies.push(trip.company)
    }
  })
  
  console.log('Stage companies for', stage.name, ':', companies)
  return companies
}


const getCompanyInitials = (name) => {
  if (!name) return '??'
  
  const words = name.split(' ')
  if (words.length >= 2) {
    return (words[0][0] + words[1][0]).toUpperCase()
  }
  return name.substring(0, 2).toUpperCase()
}

const getTrustRating = (company) => {
  const ratings = {
    'Kenya Coffee Logistics Ltd': 4.8,
    'Kenya Highland Transport': 4.6,
    'Mombasa Express Cargo': 4.4,
    'East Africa Shipping Lines': 4.7,
    'ООО "Грузовичок"': 4.5,
    'ИП Автобаза №1': 4.3,
    'ООО "ЖДТранс"': 4.6,
    'Kenya Ports Authority': 4.9
  }
  
  return ratings[company.name] || 4.2
}
</script>

<style scoped>
.route-map {
  @apply w-full;
}
</style>