<template>
  <div class="w-full">
    <ClientOnly>
      <LMap
        :style="`height: ${height}px; width: 100%;`"
        :zoom="3"
        :center="mapCenter"
        :use-global-leaflet="false"
        class="rounded-lg border border-base-300"
        @ready="onMapReady"
      >
        <LTileLayer 
          url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png" 
          attribution="&copy; <a href='https://www.openstreetmap.org/'>OpenStreetMap</a> contributors" 
        />
        
        <!-- Route point markers -->
        <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-base-content/70">Companies:</p>
                <div v-for="company in point.companies" :key="company.uuid" class="text-xs">
                  {{ company.name }}
                </div>
              </div>
            </div>
          </LPopup>
        </LMarker>
        
        <!-- Route lines -->
        <LPolyline 
          v-if="routeCoordinates.length > 1"
          :lat-lngs="routeCoordinates"
          :weight="3"
          :color="primaryColor"
          :opacity="0.7"
        />
      </LMap>
      
      <template #fallback>
        <div class="h-96 w-full bg-base-200 rounded-lg flex items-center justify-center">
          <p class="text-base-content/60">{{ t('routeMap.states.loading') }}</p>
        </div>
      </template>
    </ClientOnly>
  </div>
</template>

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

const { t } = useI18n()
const primaryColor = 'var(--color-primary, #3b82f6)'

const routePoints = computed(() => {
  const points = []
  
  props.stages.forEach((stage) => {
    if (stage.stageType === 'transport') {
      // Source point with real coordinates
      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 || t('routeMap.points.source'),
            lat: stage.sourceLatitude,
            lng: stage.sourceLongitude,
            stage: stage,
            companies: getStageCompanies(stage)
          })
        }
      }
      
      // Destination point with real coordinates
      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 || t('routeMap.points.destination'),
            lat: stage.destinationLatitude,
            lng: stage.destinationLongitude,
            stage: stage,
            companies: getStageCompanies(stage)
          })
        }
      }
    } else {
      // Service stage with real coordinates
      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 || t('routeMap.points.service'),
            lat: stage.locationLatitude,
            lng: stage.locationLongitude,
            stage: stage,
            companies: getStageCompanies(stage)
          })
        }
      }
    }
  })
  
  return points
})

// Compute map center from point coordinates
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]
})

// Fix marker icons for local usage
const onMapReady = (map) => {
  // Import Leaflet directly to configure icons
  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]
      })
      
      // Remove prefix from 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)
    }
  })
  
  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,
    'Truck LLC': 4.5,
    'Motor Depot #1': 4.3,
    'RailTrans LLC': 4.6,
    'Kenya Ports Authority': 4.9
  }
  
  return ratings[company.name] || 4.2
}
</script>
