<template>
  <div>
    <div ref="mapContainer" class="w-full h-96 rounded-lg border"></div>
    <div class="mt-2 text-sm text-gray-600">
      <p>Latitude: {{ latitude }}</p>
      <p>Longitude: {{ longitude }}</p>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, watch } from 'vue';

const props = defineProps({
  modelValue: {
    type: Object,
    default: () => ({ lat: 0, lng: 0 }),
  },
});

const emit = defineEmits(['update:modelValue']);

const mapContainer = ref(null);
const latitude = ref(props.modelValue.lat);
const longitude = ref(props.modelValue.lng);
let map = null;
let marker = null;

onMounted(() => {
  initMap();
});

const initMap = () => {
  if (!window.google) {
    console.error('Google Maps not loaded');
    return;
  }

  map = new google.maps.Map(mapContainer.value, {
    center: { lat: latitude.value || 6.9271, lng: longitude.value || 79.8612 },
    zoom: 13,
  });

  marker = new google.maps.Marker({
    position: { lat: latitude.value || 6.9271, lng: longitude.value || 79.8612 },
    map: map,
    draggable: true,
  });

  map.addListener('click', (e) => {
    updatePosition(e.latLng.lat(), e.latLng.lng());
  });

  marker.addListener('dragend', (e) => {
    updatePosition(e.latLng.lat(), e.latLng.lng());
  });
};

const updatePosition = (lat, lng) => {
  latitude.value = lat;
  longitude.value = lng;
  marker.setPosition({ lat, lng });
  emit('update:modelValue', { lat, lng });
};

const getCurrentLocation = () => {
  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition((position) => {
      updatePosition(position.coords.latitude, position.coords.longitude);
      map.setCenter({ lat: position.coords.latitude, lng: position.coords.longitude });
    });
  }
};

defineExpose({ getCurrentLocation });
</script>
