<script lang="ts">
  import { MapLibre, GeoJSON, SymbolLayer } from 'svelte-maplibre';
  import { onDestroy } from 'svelte';
  import type { GeoJSON as GeoJSONType, Position, Feature, Point } from 'geojson';
    import pointIcon from '$lib/assets/point.png';

  type LngLat = [number, number];

  // Маршрут для анимации
  const route: LngLat[] = [
    [30.5, 50.5],
    [30.6, 50.55],
    [30.7, 50.5],
    [30.8, 50.45],
    [30.7, 50.4],
    [30.5, 50.45],
    [30.5, 50.5]
  ];
    const promoteId = 'id';
//   let isAnimating = false;
  // Функция для расчёта азимута (поворота)
  function getBearing(start: LngLat, end: LngLat): number {
    const [lng1, lat1] = start;
    const [lng2, lat2] = end;
    const dLng = lng2 - lng1;
    const y = Math.sin(dLng) * Math.cos(lat2);
    const x = Math.cos(lat1) * Math.sin(lat2) - Math.sin(lat1) * Math.cos(lat2) * Math.cos(dLng);
    return (Math.atan2(y, x) * 180) / Math.PI;
  }

  let currentSegment = 0;
  let progress = 0;
  const speed = 0.005;
  let animationId: number | null = null;
  let coord = (route[0] as Position)

  // ✅ GeoJSON данные с вашей структурой
  let geojsonData: GeoJSONType = ({
    type: 'FeatureCollection',
    features: [
      {
        type: 'Feature',
        geometry: {
          type: 'Point',
          coordinates: coord
        },
        properties: {
          bearing: 0,
          // можно добавить любые другие свойства
          id: 'animated-point-1',
          name: 'Моя точка'
        }
      }
    ]
  });

  function getCurrentPosition(segment: number, t: number): Position {
    const start = route[segment];
    const end = route[(segment + 1) % route.length];
    return [
      start[0] + (end[0] - start[0]) * t,
      start[1] + (end[1] - start[1]) * t
    ] as const;
  }

  function animate() {
    progress += speed;
    if (progress >= 1) {
      progress = 0;
      currentSegment = (currentSegment + 1) % route.length;
    }

    const startPos = route[currentSegment];
    const endPos = route[(currentSegment + 1) % route.length];
    const currentPos = getCurrentPosition(currentSegment, progress);
    const bearing = getBearing(startPos, endPos);

    // // ✅ Обновляем данные
    // const updatedFeature: Feature<Point> = {
    //   type: 'Feature',
    //   geometry: {
    //     type: 'Point',
    //     coordinates: currentPos as Position
    //   },
    //   properties: {
    //     bearing: bearing,
    //     id: 'animated-point',
    //     name: 'Моя точка'
    //   }
    // };
    coord = currentPos
    // geojsonData.features[0].geometry.coordinates = currentPos as Position;
    // console.log(geojsonData.features[0].geometry.coordinates = currentPos as Position)
    // geojsonData = {
    //   type: 'FeatureCollection',
    //   features: [updatedFeature]
    // };

    animationId = requestAnimationFrame(animate);
  }

  // Запускаем анимацию
//   animate();

  onDestroy(() => {
    if (animationId) cancelAnimationFrame(animationId);
  });
</script>

<MapLibre
  center={[30.5, 50.5]}
  zoom={12}
  class="h-[80vh]"
  images={[
            {id: 'point', url: pointIcon},
        ]}
  style="https://basemaps.cartocdn.com/gl/positron-gl-style/style.json"
  standardControls
>
  <!-- ✅ Ваш компонент GeoJSON с SymbolLayer -->
  <GeoJSON data={geojsonData} id="animated-pointf" promoteId={promoteId}>
    <SymbolLayer 
      hoverCursor="pointer"
      layout={{
        "icon-image": 'point',
        "icon-size": 0.6,
        // Добавляем поворот на основе свойства bearing
        "icon-rotate": ['get', 'bearing'],
        "icon-rotation-alignment": 'map',
        "icon-overlap": 'always',
        "icon-ignore-placement": true
      }}
    />
  </GeoJSON>
</MapLibre>
<button onclick={animate} class="cursor-pointer">
        <p>Кнопка 1</p>
    </button>
    <button onclick={() => {if (animationId) cancelAnimationFrame(animationId);}} class="cursor-pointer">
        <p>Кнопка 2</p>
    </button>