<template>
  <div>
    <div id="map"></div>
  </div>
</template>

<script setup lang="ts">
import { onMounted } from "vue";
import Map from "ol/Map";
import View from "ol/View";
import { fromLonLat } from "ol/proj";
import { Tile as TileLayer } from "ol/layer";
import { OSM } from "ol/source";
import Feature from "ol/Feature";
import Point from "ol/geom/Point";
import Circle from "ol/geom/Circle";
import VectorLayer from "ol/layer/Vector";
import VectorSource from "ol/source/Vector";
import { Style, Icon, Fill, Stroke } from "ol/style";

onMounted(() => {
  const map = new Map({
    target: "map",
    layers: [
      new TileLayer({
        source: new OSM(),
      }),
    ],
    view: new View({
      center: fromLonLat([98.981716, 18.7883]),
      zoom: 12,
    }),
  });

  if ("geolocation" in navigator) {
    navigator.geolocation.getCurrentPosition((position) => {
      console.log(position);
      const lon = position.coords.longitude;
      const lat = position.coords.latitude;
      const coordinates = fromLonLat([lon, lat]);

      currentLocationFeature.setGeometry(new Point(coordinates));
      map.getView().setCenter(coordinates);
    });
  }

  // สร้าง feature สำหรับตำแหน่งปัจจุบัน
  const currentLocationFeature = new Feature({
    geometry: new Point(fromLonLat([98.981716, 18.7883])),
  });

  currentLocationFeature.setStyle(
    new Style({
      image: new Icon({
        src: "https://assets.untappd.com/site/beer_logos_hd/beer-4817317_108bb_hd.jpeg",
        scale: 0.02,
      }),
    })
  );

  const currentLocationLayer = new VectorLayer({
    source: new VectorSource({
      features: [currentLocationFeature],
    }),
  });

  map.addLayer(currentLocationLayer);

  // สร้างวงรอบ
  const circleFeature = new Feature({
    geometry: new Circle(fromLonLat([98.981716, 18.7883]), 1000),
  });

  circleFeature.setStyle(
    new Style({
      fill: new Fill({
        color: "rgba(2, 169, 152, 0.2)",
      }),
      stroke: new Stroke({
        color: "rgb(2, 169, 152)",
        width: 2,
      }),
    })
  );
  const circleLayer = new VectorLayer({
    source: new VectorSource({
      features: [circleFeature],
    }),
  });

  map.addLayer(circleLayer);
});
</script>

<style scoped>
#map {
  width: 100%;
  height: 400px;
}
</style>
