import type {YMapLocationRequest} from '@yandex/ymaps3-types';

ymaps3.ready.then(() => {
  ymaps3.import.registerCdn('https://cdn.jsdelivr.net/npm/{package}', '@yandex/ymaps3-default-ui-theme@0.0');
});

const LOCATION: YMapLocationRequest = {
  center: [0, 0],
  zoom: 2
};

const API_KEY = '970175fb-5baf-4a4f-a632-9e23b8321f37';
let map;
let marker;
let geocodedData = [];

// Адреса и их координаты (получены через геокодирование)
const addresses = [
    { text: "г. Липецк, ул. Кузнечная, 10А" },
    { text: "г. Липецк, ул. Гоголя, 60" },
    { text: "г. Липецк, б-р Есенина, 8А" }
];

// Загрузка API и инициализация карты
initMap();

async function initMap() {
    try {
        await ymaps3.ready;

        const { YMap, YMapDefaultSchemeLayer, YMapDefaultFeaturesLayer, YMapMarker, Placemark, modules } = ymaps3;
        const { YMapDefaultMarker } = await ymaps3.import('@yandex/ymaps3-default-ui-theme');
//        const { YMapDefaultMarker } = await ymaps3.import('@yandex/ymaps3-markers');

        document.getElementById('loading').style.display = 'block';

        // Геокодирование всех адресов
        geocodedData = await Promise.all(
            addresses.map((address, index) => geocodeAddress(address, index))
        );
        console.log(geocodedData);

        // Удаление загрузочного элемента
        document.getElementById('loading').style.display = 'none';

        // Инициализация карты с первым адресом
        if (geocodedData[0] && geocodedData[0].coords) {
            map = new YMap(
                document.getElementById('map'),
                {
                    location : {
                        center: geocodedData[0].coords,
                        zoom: 17,
                    },
                    controls: ['zoomControl']
                },
                [
                    // Add a map scheme layer
                    new YMapDefaultSchemeLayer({}),
                    // Add a layer of geo objects to display the markers
                    new YMapDefaultFeaturesLayer({})
                ]
            );

            // Создание метки
            marker = new YMapDefaultMarker({
                coordinates: geocodedData[0].coords,
                title: geocodedData[0].displayName,
                color: 'blue'
            });

            map.addChild(marker);
            setupAddressClickHandlers();
        } else {
            showError("Не удалось получить координаты для первого адреса");
        }
    } catch (error) {
        console.error("Ошибка инициализации карты: ", error);
        showError("Произошла ошибка при загрузке карты");
    }
}

// Геокодирование отдельного адреса
function geocodeAddress(address, index) {
    return new Promise((resolve, reject) => {
//        const httpApiUrl = 'https://geocode-maps.yandex.ru/1.x';
//        const queryString = new URLSearchParams({
//            apikey: API_KEY,
//        }).toString();
//        const fullUrl = `${url}?${queryString}`;
//
//        const response = fetch(fullUrl);

//        const searchService = new ymaps3.SearchService();
        const search = ymaps3.search(address).then((res) => {
            if (!res.length || res.length === 0) {
                console.warn(`Адрес "${address}" не найден`);
                resolve({ address, coords: null });
                return;
            }
            const coords = res[0].geometry.coordinates;
            resolve({
                address,
                coords,
                index,
                displayName: "Андромеда"//res[0].properties.name
            });
        }).catch((err) => {
                console.error(`Ошибка геокодирования адреса "${address}": `, err);
                resolve({ address, coords: null });
        });
    });
}

// Обработка кликов по адресам
function setupAddressClickHandlers() {
    document.querySelectorAll('.map-address').forEach(item => {
        item.addEventListener('click', () => {
            const index = parseInt(item.getAttribute('data-index'));
            const location = geocodedData[index];

            if (!location || !location.coords) {
                showError(`Не удалось найти координаты для адреса "${location.address}"`);
                return;
            }

            // Обновление интерфейса
            document.querySelectorAll('.map-address').forEach(el => {
                el.classList.remove('active');
            });

            // Добавление активного класса текущему
            item.classList.add('active');

            // Обновление карты
            marker.update({
                coordinates: location.coords,
                title: location.displayName,
                color: 'blue'
            });
            map.setLocation({
                center: location.coords,
                zoom: 17
            });
});
    });
}

// Отображение ошибок
function showError(message) {
    const errorEl = document.getElementById('error-message');
    errorEl.textContent = message;
    errorEl.style.display = 'block';
    setTimeout(() => {
        errorEl.style.display = 'none';
    }, 5000);
}