// source --> https://rigasvasara.lv/wp-content/themes/vasara2026/assets/js/map-ol.js?ver=1.0.2 
(function($) {

    const dateFormat = 'dd.mm.yy';

    $(document).ready(function() {

        let map, loader, eventJSON, zoomhint, hintTimeout, markers;

        const allMarkers = [];

        if ($('#event-map').length) {
            zoomhint = $('.zoom-hint');
            loader = $('.map-loader');

            let waitForAPI = window.setInterval(function() {
                if (typeof L === 'object') {
                    initMap();
                    clearInterval(waitForAPI);
                }
            }, 50);
        }

        function initMap() {
            $(loader).hide();
            map = L.map('event-map').setView([56.965020677726315, 24.146890013042213], 12);

            map.scrollWheelZoom.disable();

            map.getContainer().addEventListener('wheel', function (e) {
                if (!e.ctrlKey) {
                    // e.preventDefault();
                    // e.stopPropagation();

                    $(zoomhint).show();
                    clearTimeout(hintTimeout);
                    hintTimeout = setTimeout(() => {
                        $(zoomhint).hide();
                    }, 1500);

                    return;
                }

                e.preventDefault();
                e.stopPropagation();

                map.scrollWheelZoom.enable();

                clearTimeout(map._ctrlZoomTimeout);
                map._ctrlZoomTimeout = setTimeout(() => {
                    map.scrollWheelZoom.disable();
                }, 1000);
            }, { passive: false });

            eventJSON = $('#event-json').val();
            if(eventJSON) {
                eventJSON = JSON.parse(eventJSON);
            }

            // L.tileLayer('https://map.webserveris.lv/styles/latvia-violet/{z}/{x}/{y}.png', {
            //     maxZoom: 20,
            //      attribution: '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
            // }).addTo(map);

            L.rectangle(map.getBounds(), {
                color: null,
                fillColor: '#d9b3ff',
                fillOpacity: 0.3,
                interactive: false
            }).addTo(map);

            L.tileLayer('https://tile.openstreetmap.org/{z}/{x}/{y}.png', {
                attribution: '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
            }).addTo(map);

            markers = L.markerClusterGroup();

            $.each(eventJSON, function(_key, _event) {

                // const lat = parseFloat(_event.event_coordinates[0]);
                // const lon = parseFloat(_event.event_coordinates[1]);

                let expired = '';
                const offset = (Math.random() - 0.5) * 0.0005;
                const lat = parseFloat(_event.event_coordinates[0]) + offset;
                const lon = parseFloat(_event.event_coordinates[1]) + offset;

                const _now = new Date();
                const _ends = _event.event_ends;

                const [_datePart, _timePart] = _ends.split(' ');
                const [_day, _month, _year] = _datePart.split('.').map(Number);
                const [_hours, _minutes] = _timePart.split(':').map(Number);

                const _targetDate = new Date(_year, _month - 1, _day, _hours, _minutes);

                if(_now > _targetDate) {
                    expired = 'map__event-expired';
                }

                const icon = L.divIcon({
                    className: '',
                    html: `<div class="map-marker ${expired}" style="background-image: url('${_event.event_category.icon}');"></div>`,
                    iconSize: [52, 52],
                    iconAnchor: [20, 20]
                });
                    
                let eventStartTime = 'Laiks: ' + _event.event_starts_time_formated;

                if(_event.event_all_day == true) eventStartTime = 'Laiks: Visu dienu';

                let eventTypes = '';

                $.each(_event.event_type, function(index, value) {
                    eventTypes += '\
                        <div class="event-popup-type">\
                            <img src="' + value.icon + '" alt="' + value.title + '" onload="SVGInject(this)">\
                            <span class="event-popup-type-title">' + value.title + '</span>\
                        </div>\
                    ';
                });

                let popupHtml = '\
                    <a class="event-popup" href="' + _event.event_url + '" target="_blank" aria-label="Atvērt pasākumu: ' + _event.event_title + '">\
                        <div class="event-popup-image">\
                            <img src="' + _event.event_image + '" alt="' + _event.event_title + '">\
                        </div>\
                        <div class="event-popup-meta">\
                            <div class="event-popup-meta-item">\
                                <img src="/wp-content/themes/wb/assets/images/rs-popup-date.svg" alt="Datums" onload="SVGInject(this)">\
                                <span class="event-popup-meta-text" tabindex="0" aria-label="' + _event.event_date_from_to + '">' + _event.event_date_from_to + '</span>\
                            </div>\
                            <div class="event-popup-meta-item">\
                                <img src="/wp-content/themes/wb/assets/images/rs-popup-time.svg" alt="Laiks" onload="SVGInject(this)">\
                                <span class="event-popup-meta-text" tabindex="0" aria-label="' + eventStartTime + '">' + eventStartTime + '</span>\
                            </div>\
                        </div>\
                        <div class="event-popup-title" tabindex="0" aria-label="' + _event.event_title + '">' + _event.event_title + '</div>\
                        <div class="event-popup-types-list">' + eventTypes + '</div>\
                    </a>\
                ';

                const marker = L.marker([lat, lon], { icon });
                marker.bindPopup(popupHtml);
                markers.addLayer(marker);

                allMarkers.push({
                    marker: marker,
                    data: _event
                });

                // marker.on('click', function () {
                //     map.flyTo(marker.getLatLng(), map.getZoom());
                //     // marker.openPopup();
                // });
            });

            map.addLayer(markers);

            if($('.init-datepicker').length) {

                let filter_from = '';
                let filter_to = '';

                const today = new Date();
                const min = new Date(2025, 7, 1);

                const fromDateObj = filter_from ? parseDateFromString(filter_from) : null;
                const toDateObj = filter_to ? parseDateFromString(filter_to) : null;

                $.datepicker.setDefaults($.datepicker.regional['lv']);

                let fromOptions = {
                    dateFormat: dateFormat,
                    // minDate: fromDateObj || today,
                    minDate: min,
                    defaultDate: today,
                    onSelect: function(selectedDate) {
                        var date = $(this).datepicker('getDate');
                        $('#map-filter-date-to').datepicker("option", "minDate", date);
                        eventFilterApply();
                    }
                };

                if (toDateObj) {
                    fromOptions.maxDate = toDateObj;
                }

                let from = $('#map-filter-date-from').datepicker(fromOptions);
                $('#map-filter-date-from').datepicker("setDate", today);

                let to = $('#map-filter-date-to').datepicker({
                    dateFormat: dateFormat,
                    minDate: fromDateObj || today,

                    onSelect: function(selectedDate) {
                        var date = $(this).datepicker('getDate');
                        eventFilterApply();
                    }
                });

                eventFilterApply();
            }

        }
        
        

        $('#map-type').change(function() {
            eventFilterApply();
        });

        $('#map-entrance').change(function() {
            eventFilterApply();
        });

        $('.map-filter-hide').click(function() {
            let filters = $('.map-filters');

            $(filters).removeClass('fade-in').addClass('fade-out');
            $('.map-filter-show').removeClass('fade-out').addClass('fade-in').css('display', 'inline-flex');

            setTimeout(function() {
                $(filters).hide();
            }, 500);
        });

        $('.map-filter-show').click(function() {
            $('.map-filters').removeClass('fade-out').addClass('fade-in').show();

            $(this).removeClass('fade-in').addClass('fade-out');

            setTimeout(function() {
                $('.map-filter-show').hide();
            },500); 
        });

        function eventFilterApply() {
            
            const typeFilter = parseInt($('#map-type option:selected').val());
            const pricingFilter = $('#map-entrance option:selected').val();
            const fromVal = $('#map-filter-date-from').val();
            const toVal = $('#map-filter-date-to').val();

            const fromDate = fromVal ? parseDate(fromVal + ' 00:00') : null;
            const toDate = toVal ? parseDate(toVal + ' 23:59') : null;

            let matchIds = [];

            markers.clearLayers();

            allMarkers.forEach(({ marker, data }) => {

                let typeMatch = false;
                let pricingMatch = false;
                let dateMatch = false;

                const start = parseDate(data.event_starts);
                const end = parseDate(data.event_ends);

                if (fromDate && toDate) {
                    if(end >= fromDate && start <= toDate) {
                        dateMatch = true;
                    }
                } else if (fromDate) {
                    if(end >= fromDate) {
                        dateMatch = true;
                    }
                } else if (toDate) {
                    if(start <= toDate) {
                        dateMatch = true;
                    }
                } else {
                    dateMatch = true;
                }

                if(typeFilter) {
                    $.each(data.event_type, function(index, value) {
                        if(value.id == typeFilter) typeMatch = true;
                    });
                } else {
                    typeMatch = true;
                }
 
                if(pricingFilter) {
                    if(pricingFilter == 'free' && data.event_free == 1) {
                        pricingMatch = true;
                    } else if(pricingFilter == 'paid' && !data.event_free) {
                        pricingMatch = true;
                    }
                } else {
                    pricingMatch = true;
                }

                if (pricingMatch && typeMatch && dateMatch) {
                    matchIds.push(data.event_id);
                    markers.addLayer(marker);
                }
            });

            $('.map-event-list .event-card').each(function() {
                let eid = $(this).data('eid');

                if(matchIds.includes(eid)) {
                    $(this).show();
                } else {
                    $(this).hide();
                }
            });
        }

        function parseDate(dateStr) {
            const parts = dateStr.split(/[\s.:]/);
            const [dd, mm, yyyy, hh = '00', min = '00'] = parts;
            return new Date(`${yyyy}-${mm}-${dd}T${hh}:${min}`);
        }

    });

})(jQuery);