---
import Layout from 'layouts/PageLayout.astro'
import 'leaflet/dist/leaflet.css'
import 'leaflet-routing-machine/dist/leaflet-routing-machine.css'
import FormContainer from 'components/ui/Form.astro'
import Input from 'components/Input.astro'
import Button from 'components/ui/Button.astro'

const metadata = {
  title: 'Maps',
  ignoreTitleTemplate: true,
}
---

<Layout metadata={metadata}>

  <div class="h-[calc(100vh-16rem)] flex flex-col">
    <div class="w-full h-96 grow" id="map" />
    <Button id="test-btn">test</Button>
  </div>
  <!-- TODO: faire en sort que le style soit propre -->
  <!-- for remouve footer -->
  <!-- <div slot="footer"></div> -->
  <!-- penser a rm  11 au rem au dessus pour la taille -->
</Layout>

<script>
  import L from 'leaflet'
  import markerShadow from "leaflet/dist/images/marker-shadow.png"
  import markerIcon from "leaflet/dist/images/marker-icon.png"
  import 'leaflet-routing-machine/dist/leaflet-routing-machine.js'
  import 'leaflet-control-geocoder/dist/Control.Geocoder.js'

  const icon = {icon: new L.Icon({iconUrl: markerIcon.src, shadowUrl: markerShadow.src, iconAnchor: [13,41]})}

  // declare map
  const map = L.map('map', {
    center: [51.5, -0.09],
    zoom: 13,
    preferCanvas: true,
    zoomControl: false
  })
  L.tileLayer('https://tile.openstreetmap.org/{z}/{x}/{y}.png', {
    maxZoom: 19,
    attribution: '&copy; <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a>'
  }).addTo(map)

  // move zoom ctl to bottom
  L.control.zoom({
    position: 'bottomleft'
  }).addTo(map);

  const routing = L.Routing.control({
    // utile pour afficher des route stocké
    // waypoints: [
    //   L.latLng(46.6705431, -1.4269698),
    //   L.latLng(47.218536, -1.554075)
    // ],
    routeWhileDragging: true,
    geocoder: L.Control.Geocoder.nominatim(),
    position: 'topleft',
    showAlternatives: true,
    reverseWaypoints: true,
    altLineOptions: {
      missingRouteTolerance: 50,
      extendToWaypoints: true,
      styles: [
        {color: 'black', opacity: 0.15, weight: 9},
        {color: 'white', opacity: 0.2, weight: 6},
        {color: 'blue', opacity: 5, weight: 2}
      ]
    }
  }).addTo(map).on('routeselected', (e) => {
    console.log("iténeraire choisie")
    console.log(e)
  }).on('routesfound', (e) =>{
    console.log("route trouvé")
    console.log(e)
  })
  document.querySelector<HTMLButtonElement>('#test-btn')?.addEventListener('click', () => {
    routing.setWaypoints(
      [L.latLng(46.6705431, -1.4269698),L.latLng(47.218536, -1.554075)]
    )
    routing.route();
  })

</script>
