{% extends 'default.html.twig' %}

{% block content %}
{% set journal_entries = page.collection() %}
{% set stories_page = grav.pages.find(page.parent().route ~ '/stories') %}
{% set story_entries = stories_page ? stories_page.children.published() : [] %}

{% set all_items = [] %}
{% for e in journal_entries %}
    {% set all_items = all_items|merge([{'type': 'journal', 'page': e, 'date': e.date}]) %}
{% endfor %}
{% for s in story_entries %}
    {% set all_items = all_items|merge([{'type': 'story', 'page': s, 'date': s.date}]) %}
{% endfor %}
{% set all_items = all_items|sort((a, b) => a.date < b.date ? 1 : -1) %}

{# Collect GPS entries for mini-map #}
{% set map_entries = [] %}
{% for item in all_items %}
    {% if item.type == 'journal' and item.page.header.lat is not empty and item.page.header.lng is not empty %}
        {% set map_entries = map_entries|merge([{
            'lat': item.page.header.lat,
            'lng': item.page.header.lng,
            'title': item.page.title,
            'slug': item.page.slug,
            'url': item.page.url
        }]) %}
    {% endif %}
{% endfor %}

{% if map_entries|length > 0 %}
<div class="feed-map-wrap">
    <div class="feed-map" id="feed-map"></div>
    <a class="feed-map-link" href="{{ page.parent().url }}/map">View full map →</a>
</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="{{ url('theme://js/maplibre-utils.js') }}"></script>
<script>
var FEED_ENTRIES = {{ map_entries|json_encode|raw }};

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

feedMap.on('load', function () {
    var bounds = new maplibregl.LngLatBounds();
    var coords = [];

    FEED_ENTRIES.forEach(function (entry, i) {
        var isLatest = (i === FEED_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(feedMap); });
        el.addEventListener('mouseleave', function () { popup.remove(); });
        el.addEventListener('click', function () { window.location.href = entry.url; });

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

    MapUtils.addJourneyLine(feedMap, coords, 'feed-journey');

    if (FEED_ENTRIES.length === 1) {
        feedMap.jumpTo({ center: coords[0], zoom: 10 });
    } else {
        feedMap.fitBounds(bounds, { padding: 60, maxZoom: 11 });
    }
});
</script>
{% endif %}

<div class="feed">
    {% if all_items|length > 0 %}
        {% for item in all_items %}
            {% set entry = item.page %}
            {% set hero = null %}
            {% if entry.header.hero_image and entry.media[entry.header.hero_image] is defined %}
                {% set hero = entry.media[entry.header.hero_image] %}
            {% elseif entry.media.images|length > 0 %}
                {% set hero = entry.media.images|first %}
            {% endif %}

            {% if item.type == 'journal' %}
            <article class="entry-card" id="entry-{{ entry.slug }}" data-lat="{{ entry.header.lat }}" data-lng="{{ entry.header.lng }}">
                <a class="entry-card-inner" href="{{ entry.url }}">
                    {% if hero %}
                    <div class="entry-card-photo">
                        <img src="{{ hero.cropResize(720, 405).url }}" alt="{{ entry.title }}" loading="lazy">
                        <div class="entry-card-photo-overlay">
                            <time class="entry-date-overlay" datetime="{{ entry.date|date('Y-m-d') }}">
                                {{ entry.date|date('d M Y')|upper }}
                            </time>
                            {% if entry.header.location_city or entry.header.location_country %}
                            <span class="entry-location-overlay">
                                📍
                                {% if entry.header.location_city %}{{ entry.header.location_city|slice(0,20) }}{% endif %}
                                {% if entry.header.location_city and entry.header.location_country %}, {% endif %}
                                {% if entry.header.location_country %}{{ entry.header.location_country }}{% endif %}
                            </span>
                            {% endif %}
                        </div>
                    </div>
                    {% else %}
                    <div class="entry-card-textmeta">
                        <time class="entry-date-plain" datetime="{{ entry.date|date('Y-m-d') }}">
                            {{ entry.date|date('d M Y')|upper }}
                        </time>
                        {% if entry.header.location_city or entry.header.location_country %}
                        <span class="entry-location-plain">
                            {%- set _loc = [] -%}
                            {%- if entry.header.location_city -%}{%- set _loc = _loc|merge([entry.header.location_city]) -%}{%- endif -%}
                            {%- if entry.header.location_country -%}{%- set _loc = _loc|merge([entry.header.location_country]) -%}{%- endif -%}
                            📍 {{ _loc|join(', ') }}
                        </span>
                        {% endif %}
                    </div>
                    {% endif %}
                    <div class="entry-card-body">
                        <h2 class="entry-title">{{ entry.title }}</h2>
                        <p class="entry-excerpt">{{ entry.summary|striptags|slice(0, 250)|trim }}</p>
                        <span class="entry-read-more">Read entry →</span>
                    </div>
                </a>
            </article>
            {% else %}
            <article class="entry-card entry-card--story" id="entry-{{ entry.slug }}">
                <a class="entry-card-inner" href="{{ entry.url }}">
                    {% if hero %}
                    <div class="entry-card-photo entry-card-photo--story">
                        <img src="{{ hero.cropResize(720, 405).url }}" alt="{{ entry.title }}" loading="lazy">
                    </div>
                    {% endif %}
                    <div class="entry-card-body">
                        <span class="story-badge">✦ Story</span>
                        <h2 class="entry-title">{{ entry.title }}</h2>
                    </div>
                </a>
            </article>
            {% endif %}
        {% endfor %}
    {% else %}
        <p class="feed-empty">No entries yet. The journey is about to begin.</p>
    {% endif %}
</div>
{% endblock %}
