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

const props = defineProps({
    points: {
        type: Array,
        required: true,
    },
});

const isMapView = ref(true);
let mapInstance = null;

const toggleView = () => {
    isMapView.value = !isMapView.value;
    if (isMapView.value && !mapInstance) {
        initMap();
    }
};

const initMap = () => {
    if (!window.ymaps) return;

    ymaps.ready(() => {
        mapInstance = new ymaps.Map('map', {
            center: [51.768199, 55.096955],
            zoom: 7,
            controls: ['zoomControl'],
        });
        drawPlacemarks(props.points);
    });
};

function drawPlacemarks(pointsArr) {
    if (!mapInstance) return;

    mapInstance.geoObjects.removeAll();

    pointsArr.forEach((point) => {
        const placemark = new ymaps.Placemark(
            [parseFloat(point.latitude), parseFloat(point.longitude)],
            {
                balloonContent: `<strong>${point.name}</strong><br>${point.region}, ${point.area}`,
            },
            {
                preset: 'islands#redIcon',
            },
        );
        mapInstance.geoObjects.add(placemark);
    });
}

watch(
    () => props.points,
    (newValue) => {
        if (mapInstance) {
            drawPlacemarks(newValue);
        }
    },
    { deep: true },
);

onMounted(() => {
    if (isMapView.value) {
        initMap();
    }
});
</script>

<template>
    <div>
        <button class="btn btn-primary" @click="toggleView">
            {{ isMapView ? 'Список' : 'Карта' }}
        </button>

        <div v-show="isMapView" style="margin-top: 10px">
            <div
                id="map"
                style="width: 100%; height: calc(100vh - 155px); background-color: #eee; border: 1px solid #ccc"
            ></div>
        </div>

        <div v-show="!isMapView" style="margin-top: 10px">
            <ul class="list-group">
                <li class="list-group-item" v-for="(point, index) in points" :key="index">
                    <strong>{{ point.name }}</strong
                    ><br />
                    Регион: {{ point.region }}<br />
                    Область: {{ point.area }}<br />
                    Координаты: {{ point.latitude }}, {{ point.longitude }}
                </li>
            </ul>
        </div>
    </div>
</template>
