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

{% block content %}
{% set trips_page = grav.pages.find('/trips') %}
{% set trips = trips_page ? trips_page.children.published() : [] %}

<div class="gpx-manager">
    <h1 class="gpx-manager__title">GPX Files</h1>

    {% if trips is empty %}
        <p>No trips found.</p>
    {% else %}
        {% for trip in trips %}
        <section class="gpx-trip" data-route="{{ trip.route }}">
            <h2 class="gpx-trip__name">{{ trip.title }}</h2>
            <div class="gpx-file-list" id="files-{{ trip.slug }}">
                <p class="gpx-loading">Loading…</p>
            </div>
            <form class="gpx-upload-form" data-trip-route="{{ trip.route }}">
                <label class="gpx-upload-label">
                    <input type="file" accept=".gpx,application/gpx+xml" name="file" class="gpx-file-input">
                </label>
                <button type="submit" class="gpx-upload-btn">Upload</button>
                <span class="gpx-status"></span>
            </form>
        </section>
        {% endfor %}
    {% endif %}
</div>

<style>
.gpx-manager { max-width: 720px; margin: 2rem auto; padding: 0 1rem; font-family: 'DM Sans', sans-serif; }
.gpx-manager__title { font-family: 'DM Serif Display', serif; font-size: 1.75rem; margin-bottom: 2rem; }
.gpx-trip { border: 1px solid #e0ddd6; border-radius: 8px; padding: 1.25rem; margin-bottom: 1.5rem; }
.gpx-trip__name { font-size: 1.1rem; font-weight: 600; margin: 0 0 1rem; }
.gpx-table { width: 100%; border-collapse: collapse; font-size: 0.875rem; margin-bottom: 1rem; }
.gpx-table th { text-align: left; color: #666; font-weight: 500; padding: 0.25rem 0.5rem; border-bottom: 1px solid #e0ddd6; }
.gpx-table td { padding: 0.5rem; border-bottom: 1px solid #f0ede8; }
.gpx-empty, .gpx-loading { color: #888; font-size: 0.875rem; margin-bottom: 0.75rem; }
.gpx-upload-form { display: flex; align-items: center; gap: 0.75rem; flex-wrap: wrap; margin-top: 0.75rem; }
.gpx-upload-btn { background: #1F6B5A; color: #fff; border: none; border-radius: 5px; padding: 0.4rem 1rem; font-size: 0.875rem; cursor: pointer; }
.gpx-upload-btn:disabled { opacity: 0.5; cursor: default; }
.gpx-delete { background: none; border: 1px solid #ccc; border-radius: 4px; padding: 0.2rem 0.5rem; font-size: 0.8rem; cursor: pointer; color: #c0392b; }
.gpx-delete:disabled { opacity: 0.5; }
.gpx-status { font-size: 0.8rem; color: #555; }
.gpx-status.error { color: #c0392b; }
</style>

<script>
const API = '/api/v1';

function formatSize(bytes) {
    if (bytes >= 1048576) return (bytes / 1048576).toFixed(1) + ' MB';
    return (bytes / 1024).toFixed(0) + ' KB';
}

function slugifyFilename(filename) {
    const lastDot = filename.lastIndexOf('.');
    const name = lastDot > 0 ? filename.slice(0, lastDot) : filename;
    const ext  = lastDot > 0 ? filename.slice(lastDot).toLowerCase() : '';
    const slug = name.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/-+/g, '-').replace(/^-|-$/g, '');
    return slug + ext;
}

function formatDate(iso) {
    return new Date(iso).toLocaleDateString(undefined, { year: 'numeric', month: 'short', day: 'numeric' });
}

async function apiFetch(url, options) {
    const res = await fetch(url, { credentials: 'include', ...options });
    if (res.status === 401) { window.location.href = '/admin'; return null; }
    return res;
}

async function loadFiles(tripRoute) {
    const res = await apiFetch(`${API}/pages${tripRoute}/media`);
    if (!res || !res.ok) return [];
    const data = await res.json();
    return (data.data || []).filter(f => f.filename.toLowerCase().endsWith('.gpx'));
}

async function renderTrip(tripEl) {
    const route = tripEl.dataset.route;
    const list = tripEl.querySelector('.gpx-file-list');
    list.innerHTML = '<p class="gpx-loading">Loading…</p>';

    const files = await loadFiles(route);

    if (files.length === 0) {
        list.innerHTML = '<p class="gpx-empty">No GPX files.</p>';
        return;
    }

    const rows = files.map(f =>
        `<tr>
            <td>${f.filename}</td>
            <td>${formatSize(f.size)}</td>
            <td>${formatDate(f.modified)}</td>
            <td><button class="gpx-delete" data-filename="${f.filename}">Delete</button></td>
        </tr>`
    ).join('');

    list.innerHTML = `<table class="gpx-table">
        <thead><tr><th>File</th><th>Size</th><th>Modified</th><th></th></tr></thead>
        <tbody>${rows}</tbody>
    </table>`;

    list.querySelectorAll('.gpx-delete').forEach(btn => {
        btn.addEventListener('click', async () => {
            if (!confirm(`Delete ${btn.dataset.filename}?`)) return;
            btn.disabled = true;
            const res = await apiFetch(
                `${API}/pages${route}/media/${encodeURIComponent(btn.dataset.filename)}`,
                { method: 'DELETE' }
            );
            if (res && (res.ok || res.status === 204)) {
                await renderTrip(tripEl);
            } else {
                btn.disabled = false;
                alert('Delete failed — check console.');
            }
        });
    });
}

function initUpload(formEl) {
    formEl.addEventListener('submit', async e => {
        e.preventDefault();
        const route = formEl.dataset.tripRoute;
        const fileInput = formEl.querySelector('input[type=file]');
        const file = fileInput.files[0];
        const status = formEl.querySelector('.gpx-status');
        const btn = formEl.querySelector('.gpx-upload-btn');

        if (!file) { status.textContent = 'Choose a file first.'; return; }

        status.textContent = 'Uploading…';
        status.className = 'gpx-status';
        btn.disabled = true;

        const slugged = slugifyFilename(file.name);
        const fd = new FormData();
        fd.append('file', file.slice(0, file.size, file.type), slugged);

        const res = await apiFetch(`${API}/pages${route}/media`, { method: 'POST', body: fd });
        btn.disabled = false;

        if (res && res.ok) {
            status.textContent = 'Uploaded!';
            fileInput.value = '';
            await renderTrip(formEl.closest('.gpx-trip'));
            setTimeout(() => { status.textContent = ''; }, 3000);
        } else {
            const err = res ? await res.json().catch(() => ({})) : {};
            status.textContent = 'Error: ' + (err.detail || (res ? res.statusText : 'network error'));
            status.className = 'gpx-status error';
        }
    });
}

document.querySelectorAll('.gpx-trip').forEach(renderTrip);
document.querySelectorAll('.gpx-upload-form').forEach(initUpload);
</script>

{% endblock %}
