{% extends 'partials/base.html.twig' %}

{% block content %}
{% set trip_page = page.parent() %}
{% set tracker_page = grav.pages.find(page.parent().route ~ '/dailies') %}
{% set all_entries = tracker_page ? tracker_page.children.published() : [] %}

{% set gpx_urls = [] %}
{% for name, media in trip_page.media.all %}
    {% if name|split('.')|last == 'gpx' %}
        {% set gpx_urls = gpx_urls|merge([trip_page.url ~ '/' ~ name]) %}
    {% endif %}
{% endfor %}

{% set map_entries = [] %}
{% for entry in all_entries %}
    {% if entry.header.lat is not empty and entry.header.lng is not empty %}
        {% set hero_url = null %}
        {% if entry.header.hero_image and entry.media[entry.header.hero_image] is defined %}
            {% set hero_url = entry.media[entry.header.hero_image].cropResize(240, 135).url %}
        {% elseif entry.media.images|length > 0 %}
            {% set hero_url = entry.media.images|first.cropResize(240, 135).url %}
        {% endif %}
        {% set map_entries = map_entries|merge([{
            'lat': entry.header.lat|number_format(6, '.', ''),
            'lng': entry.header.lng|number_format(6, '.', ''),
            'title': entry.title,
            'date': entry.date|date('d M Y'),
            'url': entry.url,
            'hero': hero_url
        }]) %}
    {% endif %}
{% endfor %}

<div class="map-container" id="trip-map"></div>

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/maplibre-gl@4/dist/maplibre-gl.css">
<script src="https://cdn.jsdelivr.net/npm/maplibre-gl@4/dist/maplibre-gl.js"></script>
<script src="https://cdn.jsdelivr.net/npm/@mapbox/togeojson@0.16.2/togeojson.min.js"></script>
<script src="{{ url('theme://js/maplibre-utils.js') }}"></script>

<script>
var ENTRIES  = {{ map_entries|json_encode|raw }};
var GPX_URLS = {{ gpx_urls|json_encode|raw }};

var map = new maplibregl.Map({
    container: 'trip-map',
    style: MapUtils.MAP_STYLE,
    center: [20, 20],
    zoom: 2
});

map.addControl(new maplibregl.NavigationControl(), 'top-right');

if (ENTRIES.length === 0) {
    var empty = document.createElement('div');
    empty.className = 'map-empty';
    empty.textContent = 'No locations yet — entries with GPS will appear here.';
    document.getElementById('trip-map').appendChild(empty);
}

map.on('load', function () {
    /* ── GPX tracks ──────────────────────────────────────────── */
    GPX_URLS.forEach(function (url, idx) {
        fetch(url)
            .then(function (r) { return r.text(); })
            .then(function (text) {
                var xml     = new DOMParser().parseFromString(text, 'text/xml');
                var geojson = toGeoJSON.gpx(xml);
                var sid     = 'gpx-' + idx;
                map.addSource(sid, { type: 'geojson', data: geojson });
                map.addLayer({
                    id: sid + '-line', type: 'line', source: sid,
                    layout: { 'line-join': 'round', 'line-cap': 'round' },
                    paint:  { 'line-color': MapUtils.ACCENT, 'line-width': 2, 'line-opacity': 0.7 }
                });
            })
            .catch(function (err) { console.warn('GPX load failed:', url, err); });
    });

    if (ENTRIES.length === 0) return;

    /* ── Markers ─────────────────────────────────────────────── */
    var bounds = new maplibregl.LngLatBounds();
    var coords = [];

    ENTRIES.forEach(function (entry, i) {
        var isLatest = (i === ENTRIES.length - 1);
        var lngLat   = [parseFloat(entry.lng), parseFloat(entry.lat)];
        coords.push(lngLat);
        bounds.extend(lngLat);

        var el = MapUtils.createDotMarker(isLatest);
        var popup = new maplibregl.Popup({ offset: 12, closeButton: false, closeOnClick: false, className: 'map-tip-popup' })
            .setLngLat(lngLat)
            .setHTML('<span class="map-tip">' + entry.title + '</span>');
        el.addEventListener('mouseenter', function () { popup.addTo(map); });
        el.addEventListener('mouseleave', function () { popup.remove(); });
        el.addEventListener('click', function () { window.location.href = entry.url; });

        new maplibregl.Marker({ element: el }).setLngLat(lngLat).addTo(map);
    });

    /* ── Journey line ────────────────────────────────────────── */
    MapUtils.addJourneyLine(map, coords, 'journey');

    /* ── Fit bounds ──────────────────────────────────────────── */
    if (ENTRIES.length === 1) {
        map.jumpTo({ center: coords[0], zoom: 10 });
    } else {
        map.fitBounds(bounds, { padding: 100, maxZoom: 11 });
    }
});
</script>
{% endblock %}
