<!-- Unified Files View - Database + Filesystem - Collapsible Sessions -->
{% if sessions %}
    <div class="divide-y divide-gray-200 dark:divide-gray-700">
        {% for session_data in sessions %}
        {% set session = session_data.session %}
        {% set unit = session_data.unit %}
        {% set location = session_data.location %}
        {% set files = session_data.files %}

        {% if files %}
        <!-- Session Container -->
        <div class="session-container">
            <!-- Session Header - Clickable to expand/collapse -->
            <div class="px-6 py-4 bg-gray-50 dark:bg-gray-900/50 cursor-pointer hover:bg-gray-100 dark:hover:bg-gray-800/50 transition-colors"
                 onclick="toggleSession('session-{{ session.id }}', this)">
                <div class="flex items-center justify-between">
                    <div class="flex items-center gap-3">
                        <!-- Chevron indicator -->
                        <svg class="w-4 h-4 text-gray-400 transition-transform session-chevron" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5l7 7-7 7"></path>
                        </svg>
                        <svg class="w-5 h-5 text-blue-500" fill="currentColor" viewBox="0 0 20 20">
                            <path d="M2 6a2 2 0 012-2h5l2 2h5a2 2 0 012 2v6a2 2 0 01-2 2H4a2 2 0 01-2-2V6z"></path>
                        </svg>
                        <div>
                            {% set meta = session.session_metadata|fromjson if session.session_metadata else {} %}
                            {% set is_manual = meta.get('source') in ('manual_upload', 'bulk_upload') %}
                            <div class="font-semibold text-gray-900 dark:text-white">
                                {% if location %}{{ location.name }}{% else %}Unknown Location{% endif %}
                                {% if session.started_at %}
                                    &mdash;
                                    {% if session.stopped_at and not same_date(session.started_at, session.stopped_at) %}
                                        {{ session.started_at|local_date }} to {{ session.stopped_at|local_date }}
                                    {% else %}
                                        {{ session.started_at|local_date }}
                                    {% endif %}
                                {% endif %}
                            </div>
                            <div class="text-xs text-gray-500 dark:text-gray-400">
                                {% if is_manual %}
                                    {% set store = meta.get('store_name') %}
                                    Manual upload{% if store %} &mdash; Store {{ store }}{% endif %}
                                {% elif unit %}
                                    {{ unit.id }}
                                {% endif %}
                                <span class="mx-2">•</span>
                                {{ files|length }} file{{ 's' if files|length != 1 else '' }}
                            </div>
                        </div>
                    </div>
                    <div class="flex items-center gap-2">
                        <span class="px-2 py-1 text-xs rounded-full
                            {% if session.status == 'recording' %}bg-green-100 text-green-800 dark:bg-green-900/30 dark:text-green-300
                            {% elif session.status == 'completed' %}bg-blue-100 text-blue-800 dark:bg-blue-900/30 dark:text-blue-300
                            {% elif session.status == 'paused' %}bg-yellow-100 text-yellow-800 dark:bg-yellow-900/30 dark:text-yellow-300
                            {% else %}bg-gray-100 text-gray-800 dark:bg-gray-700 dark:text-gray-300{% endif %}">
                            {{ session.status or 'unknown' }}
                        </span>
                        <!-- Edit Session Times -->
                        <button onclick="event.stopPropagation(); openEditSessionModal('{{ session.id }}', '{{ session.started_at|local_datetime if session.started_at else '' }}', '{{ session.stopped_at|local_datetime if session.stopped_at else '' }}')"
                                class="px-3 py-1 text-xs bg-gray-600 text-white rounded-lg hover:bg-gray-700 transition-colors flex items-center gap-1"
                                title="Edit session times">
                            <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z"></path>
                            </svg>
                            Edit
                        </button>
                        <!-- Download All Files in Session -->
                        <button onclick="event.stopPropagation(); downloadSessionFiles('{{ session.id }}')"
                                class="px-3 py-1 text-xs bg-seismo-orange text-white rounded-lg hover:bg-seismo-navy transition-colors flex items-center gap-1"
                                title="Download all files in this session">
                            <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-4l-4 4m0 0l-4-4m4 4V4"></path>
                            </svg>
                            Download All
                        </button>
                        <!-- Delete Session -->
                        <button onclick="event.stopPropagation(); confirmDeleteSession('{{ session.id }}', '{{ files|length }}')"
                                class="px-3 py-1 text-xs bg-red-600 text-white rounded-lg hover:bg-red-700 transition-colors flex items-center gap-1"
                                title="Delete session and all files">
                            <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"></path>
                            </svg>
                            Delete
                        </button>
                    </div>
                </div>
            </div>

            <!-- Files List - Hidden by default -->
            <div id="session-{{ session.id }}" class="hidden px-6 py-2 border-t border-gray-100 dark:border-gray-700">
                <div class="space-y-1">
                    {% for file_data in files %}
                    {% set file = file_data.file %}
                    {% set exists = file_data.exists_on_disk %}
                    {% set metadata = file_data.metadata %}

                    <div class="flex items-center gap-3 px-4 py-3 hover:bg-gray-50 dark:hover:bg-gray-800/50 rounded-lg transition-colors group">
                        <!-- File Icon -->
                        {% if file.file_type == 'audio' %}
                        <svg class="w-6 h-6 text-blue-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 19V6l12-3v13M9 19c0 1.105-1.343 2-3 2s-3-.895-3-2 1.343-2 3-2 3 .895 3 2zm12-3c0 1.105-1.343 2-3 2s-3-.895-3-2 1.343-2 3-2 3 .895 3 2zM9 10l12-3"></path>
                        </svg>
                        {% elif file.file_type == 'archive' %}
                        <svg class="w-6 h-6 text-purple-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M20 13V6a2 2 0 00-2-2H6a2 2 0 00-2 2v7m16 0v5a2 2 0 01-2 2H6a2 2 0 01-2-2v-5m16 0h-2.586a1 1 0 00-.707.293l-2.414 2.414a1 1 0 01-.707.293h-3.172a1 1 0 01-.707-.293l-2.414-2.414A1 1 0 006.586 13H4"></path>
                        </svg>
                        {% elif file.file_type == 'log' %}
                        <svg class="w-6 h-6 text-gray-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"></path>
                        </svg>
                        {% elif file.file_type == 'image' %}
                        <svg class="w-6 h-6 text-green-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z"></path>
                        </svg>
                        {% elif file.file_type == 'measurement' %}
                        <svg class="w-6 h-6 text-emerald-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 19v-6a2 2 0 00-2-2H5a2 2 0 00-2 2v6a2 2 0 002 2h2a2 2 0 002-2zm0 0V9a2 2 0 012-2h2a2 2 0 012 2v10m-6 0a2 2 0 002 2h2a2 2 0 002-2m0 0V5a2 2 0 012-2h2a2 2 0 012 2v14a2 2 0 01-2 2h-2a2 2 0 01-2-2z"></path>
                        </svg>
                        {% else %}
                        <svg class="w-6 h-6 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"></path>
                        </svg>
                        {% endif %}

                        <!-- File Info -->
                        <div class="flex-1 min-w-0">
                            <div class="flex items-center gap-2">
                                <div class="font-medium text-gray-900 dark:text-white truncate">
                                    {{ file.file_path.split('/')[-1] if file.file_path else 'Unknown' }}
                                </div>
                                {% if not exists %}
                                <span class="px-2 py-0.5 text-xs bg-red-100 text-red-800 dark:bg-red-900/30 dark:text-red-300 rounded">
                                    Missing on disk
                                </span>
                                {% endif %}
                            </div>
                            <div class="text-xs text-gray-500 dark:text-gray-400 mt-0.5">
                                <!-- File Type Badge -->
                                <span class="px-1.5 py-0.5 rounded font-medium
                                    {% if file.file_type == 'audio' %}bg-blue-100 text-blue-700 dark:bg-blue-900/30 dark:text-blue-300
                                    {% elif file.file_type == 'data' %}bg-green-100 text-green-700 dark:bg-green-900/30 dark:text-green-300
                                    {% elif file.file_type == 'measurement' %}bg-emerald-100 text-emerald-700 dark:bg-emerald-900/30 dark:text-emerald-300
                                    {% elif file.file_type == 'log' %}bg-gray-100 text-gray-700 dark:bg-gray-700 dark:text-gray-300
                                    {% elif file.file_type == 'archive' %}bg-purple-100 text-purple-700 dark:bg-purple-900/30 dark:text-purple-300
                                    {% elif file.file_type == 'image' %}bg-pink-100 text-pink-700 dark:bg-pink-900/30 dark:text-pink-300
                                    {% else %}bg-gray-100 text-gray-700 dark:bg-gray-700 dark:text-gray-300{% endif %}">
                                    {{ file.file_type or 'unknown' }}
                                </span>

                                {# Leq vs Lp badge for RND files #}
                                {% if file.file_path and '_Leq_' in file.file_path %}
                                <span class="px-1.5 py-0.5 rounded font-medium bg-blue-100 text-blue-700 dark:bg-blue-900/30 dark:text-blue-300">
                                    Leq (15-min avg)
                                </span>
                                {% elif file.file_path and '_Lp' in file.file_path and file.file_path.endswith('.rnd') %}
                                <span class="px-1.5 py-0.5 rounded font-medium bg-orange-100 text-orange-700 dark:bg-orange-900/30 dark:text-orange-300">
                                    Lp (instant)
                                </span>
                                {% endif %}

                                <!-- File Size -->
                                <span class="mx-1">•</span>
                                {% if file.file_size_bytes %}
                                    {% if file.file_size_bytes < 1024 %}
                                        {{ file.file_size_bytes }} B
                                    {% elif file.file_size_bytes < 1048576 %}
                                        {{ "%.1f"|format(file.file_size_bytes / 1024) }} KB
                                    {% elif file.file_size_bytes < 1073741824 %}
                                        {{ "%.1f"|format(file.file_size_bytes / 1048576) }} MB
                                    {% else %}
                                        {{ "%.2f"|format(file.file_size_bytes / 1073741824) }} GB
                                    {% endif %}
                                {% else %}
                                    Unknown size
                                {% endif %}

                                <!-- Download Time -->
                                {% if file.downloaded_at %}
                                <span class="mx-1">•</span>
                                {{ file.downloaded_at|local_datetime }}
                                {% endif %}

                                <!-- Source Info from Metadata -->
                                {% if metadata.unit_id %}
                                <span class="mx-1">•</span>
                                from {{ metadata.unit_id }}
                                {% endif %}

                                <!-- Checksum Indicator -->
                                {% if file.checksum %}
                                <span class="mx-1" title="SHA256: {{ file.checksum[:16] }}...">
                                    <svg class="w-3 h-3 inline text-green-600" fill="currentColor" viewBox="0 0 20 20">
                                        <path fill-rule="evenodd" d="M2.166 4.999A11.954 11.954 0 0010 1.944 11.954 11.954 0 0017.834 5c.11.65.166 1.32.166 2.001 0 5.225-3.34 9.67-8 11.317C5.34 16.67 2 12.225 2 7c0-.682.057-1.35.166-2.001zm11.541 3.708a1 1 0 00-1.414-1.414L9 10.586 7.707 9.293a1 1 0 00-1.414 1.414l2 2a1 1 0 001.414 0l4-4z" clip-rule="evenodd"></path>
                                    </svg>
                                </span>
                                {% endif %}
                            </div>
                        </div>

                        <!-- Action Buttons -->
                        {% if exists %}
                        <div class="opacity-0 group-hover:opacity-100 transition-opacity flex items-center gap-2">
                            {% if file.file_type == 'measurement' or file.file_path.endswith('.rnd') %}
                            <a href="/api/projects/{{ project_id }}/files/{{ file.id }}/view-rnd"
                               onclick="event.stopPropagation();"
                               class="px-3 py-1 text-xs bg-emerald-600 text-white rounded-lg hover:bg-emerald-700 transition-colors flex items-center">
                                <svg class="w-4 h-4 inline mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 19v-6a2 2 0 00-2-2H5a2 2 0 00-2 2v6a2 2 0 002 2h2a2 2 0 002-2zm0 0V9a2 2 0 012-2h2a2 2 0 012 2v10m-6 0a2 2 0 002 2h2a2 2 0 002-2m0 0V5a2 2 0 012-2h2a2 2 0 012 2v14a2 2 0 01-2 2h-2a2 2 0 01-2-2z"></path>
                                </svg>
                                View
                            </a>
                            {% endif %}
                            {# Only show Report button for Leq files (15-min averaged data with LN percentiles) #}
                            {% if '_Leq_' in file.file_path %}
                            <a href="/api/projects/{{ project_id }}/files/{{ file.id }}/generate-report"
                               onclick="event.stopPropagation();"
                               class="px-3 py-1 text-xs bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors flex items-center"
                               title="Generate Excel Report">
                                <svg class="w-4 h-4 inline mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 17v-2m3 2v-4m3 4v-6m2 10H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"></path>
                                </svg>
                                Report
                            </a>
                            {% endif %}
                            <button onclick="event.stopPropagation(); downloadFile('{{ file.id }}')"
                                    class="px-3 py-1 text-xs bg-seismo-orange text-white rounded-lg hover:bg-seismo-navy transition-colors">
                                <svg class="w-4 h-4 inline mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-4l-4 4m0 0l-4-4m4 4V4"></path>
                                </svg>
                                Download
                            </button>
                            <button onclick="event.stopPropagation(); confirmDeleteFile('{{ file.id }}', '{{ file.file_path.split('/')[-1] if file.file_path else 'Unknown' }}')"
                                    class="px-3 py-1 text-xs bg-red-600 text-white rounded-lg hover:bg-red-700 transition-colors"
                                    title="Delete this file">
                                <svg class="w-4 h-4 inline" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"></path>
                                </svg>
                            </button>
                        </div>
                        {% endif %}
                    </div>
                    {% endfor %}
                </div>
            </div>
        </div>
        {% endif %}
        {% endfor %}
    </div>
{% else %}
    <!-- Empty State -->
    <div class="px-6 py-12 text-center">
        <svg class="w-16 h-16 mx-auto mb-4 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M7 21h10a2 2 0 002-2V9.414a1 1 0 00-.293-.707l-5.414-5.414A1 1 0 0012.586 3H7a2 2 0 00-2 2v14a2 2 0 002 2z"></path>
        </svg>
        <p class="text-gray-500 dark:text-gray-400 mb-2">No files downloaded yet</p>
        <p class="text-sm text-gray-400 dark:text-gray-500">
            Use the FTP browser above to download files from your sound level meters
        </p>
    </div>
{% endif %}

<script>
function toggleSession(sessionId, headerElement) {
    const contentDiv = document.getElementById(sessionId);
    const chevron = headerElement.querySelector('.session-chevron');

    if (!contentDiv) return;

    const isExpanded = !contentDiv.classList.contains('hidden');

    if (isExpanded) {
        // Collapse
        contentDiv.classList.add('hidden');
        chevron.style.transform = 'rotate(0deg)';
    } else {
        // Expand
        contentDiv.classList.remove('hidden');
        chevron.style.transform = 'rotate(90deg)';
    }
}

function downloadFile(fileId) {
    window.location.href = `/api/projects/{{ project_id }}/files/${fileId}/download`;
}

function downloadSessionFiles(sessionId) {
    window.location.href = `/api/projects/{{ project_id }}/sessions/${sessionId}/download-all`;
}

function confirmDeleteFile(fileId, fileName) {
    if (confirm(`Are you sure you want to delete "${fileName}"?\n\nThis action cannot be undone.`)) {
        deleteFile(fileId);
    }
}

async function deleteFile(fileId) {
    try {
        const response = await fetch(`/api/projects/{{ project_id }}/files/${fileId}`, {
            method: 'DELETE'
        });

        if (response.ok) {
            // Reload the files list
            window.location.reload();
        } else {
            const data = await response.json();
            alert(`Failed to delete file: ${data.detail || 'Unknown error'}`);
        }
    } catch (error) {
        alert(`Error deleting file: ${error.message}`);
    }
}

function confirmDeleteSession(sessionId, fileCount) {
    if (confirm(`Are you sure you want to delete this session and all ${fileCount} file(s)?\n\nThis action cannot be undone.`)) {
        deleteSession(sessionId);
    }
}

async function deleteSession(sessionId) {
    try {
        const response = await fetch(`/api/projects/{{ project_id }}/sessions/${sessionId}`, {
            method: 'DELETE'
        });

        if (response.ok) {
            // Reload the files list
            window.location.reload();
        } else {
            const data = await response.json();
            alert(`Failed to delete session: ${data.detail || 'Unknown error'}`);
        }
    } catch (error) {
        alert(`Error deleting session: ${error.message}`);
    }
}

function openEditSessionModal(sessionId, startedAt, stoppedAt) {
    document.getElementById('editSessionId').value = sessionId;
    // local_datetime filter returns "YYYY-MM-DD HH:MM" — convert to "YYYY-MM-DDTHH:MM" for datetime-local input
    document.getElementById('editStartedAt').value = startedAt ? startedAt.replace(' ', 'T') : '';
    document.getElementById('editStoppedAt').value = stoppedAt ? stoppedAt.replace(' ', 'T') : '';
    document.getElementById('editSessionModal').classList.remove('hidden');
}

function closeEditSessionModal() {
    document.getElementById('editSessionModal').classList.add('hidden');
}

async function saveSessionTimes() {
    const sessionId = document.getElementById('editSessionId').value;
    const startedAt = document.getElementById('editStartedAt').value;
    const stoppedAt = document.getElementById('editStoppedAt').value;

    try {
        const response = await fetch(`/api/projects/{{ project_id }}/sessions/${sessionId}`, {
            method: 'PATCH',
            headers: {'Content-Type': 'application/json'},
            body: JSON.stringify({
                started_at: startedAt || null,
                stopped_at: stoppedAt || null,
            })
        });

        if (response.ok) {
            closeEditSessionModal();
            window.location.reload();
        } else {
            const data = await response.json();
            alert(`Failed to update session: ${data.detail || 'Unknown error'}`);
        }
    } catch (error) {
        alert(`Error updating session: ${error.message}`);
    }
}
</script>

<!-- Edit Session Times Modal -->
<div id="editSessionModal" class="hidden fixed inset-0 z-50 flex items-center justify-center bg-black/50">
    <div class="bg-white dark:bg-gray-800 rounded-xl shadow-xl p-6 w-full max-w-sm mx-4">
        <h3 class="text-lg font-semibold text-gray-900 dark:text-white mb-4">Edit Session Times</h3>
        <input type="hidden" id="editSessionId">
        <div class="space-y-4">
            <div>
                <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Start Time</label>
                <input type="datetime-local" id="editStartedAt"
                       class="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white text-sm focus:outline-none focus:ring-2 focus:ring-blue-500">
            </div>
            <div>
                <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Stop Time</label>
                <input type="datetime-local" id="editStoppedAt"
                       class="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white text-sm focus:outline-none focus:ring-2 focus:ring-blue-500">
            </div>
        </div>
        <p class="mt-3 text-xs text-gray-500 dark:text-gray-400">Times are in your local timezone. The session label and period type will be updated automatically.</p>
        <div class="flex justify-end gap-3 mt-5">
            <button onclick="closeEditSessionModal()"
                    class="px-4 py-2 text-sm text-gray-700 dark:text-gray-300 bg-gray-100 dark:bg-gray-700 rounded-lg hover:bg-gray-200 dark:hover:bg-gray-600 transition-colors">
                Cancel
            </button>
            <button onclick="saveSessionTimes()"
                    class="px-4 py-2 text-sm text-white bg-blue-600 rounded-lg hover:bg-blue-700 transition-colors">
                Save
            </button>
        </div>
    </div>
</div>
