{% extends "base.html" %}

{% block title %}Media Viewer{% endblock %}

{% block content %}
<div class="container mt-4">
    <h1 class="text-center">Viewing Media: {{ filename }}</h1>
    <p class="text-muted text-center">MIME Type: {{ mime_type }}</p>

    <div class="media-container text-center">
        {% if mime_type.startswith("image/") %}
            <img src="{{ url_for('get_file', filename=filename) }}" alt="Image" class="img-fluid" />
        {% elif mime_type.startswith("video/") %}
            <video controls class="w-100">
                <source src="{{ url_for('get_file', filename=filename) }}" type="{{ mime_type }}">
                Your browser does not support the video tag.
            </video>
        {% elif mime_type.startswith("audio/") %}
            <audio controls class="w-100">
                <source src="{{ url_for('get_file', filename=filename) }}" type="{{ mime_type }}">
                Your browser does not support the audio element.
            </audio>
        {% elif mime_type == "application/pdf" %}
            <embed src="{{ url_for('get_file', filename=filename) }}" type="{{ mime_type }}" width="100%" height="600px">
        {% endif %}
    </div>

    <div class="d-flex justify-content-center mt-4">
        <button class="btn btn-primary me-2" onclick="toggleMetadata()">Toggle Metadata</button>
        <a href="{{ url_for('download_paste', id=paste_id) }}" class="btn btn-primary me-2">📥 Download</a>
    <a href="{{ url_for('get_file', filename=filename) }}" class="btn btn-primary me-2" target="_blank">🌐 View Raw</a>
        {% if current_user.is_authenticated %}
        <!-- Botón de favoritos, con clase "btn btn-sm btn-primary" para mantener la consistencia -->
        <button id="favorite-button" class="btn btn-sm btn-primary">
            ❤️ Add to Favorites
        </button>
        {% endif %}
    </div>

    <div class="metadata mt-4">
        <div id="metadata-content" class="metadata-content" style="display: none;">
            <table class="table table-bordered table-striped">
                <thead>
                    <tr>
                        <th>Property</th>
                        <th>Value</th>
                    </tr>
                </thead>
                <tbody>
                    {% if metadata %}
                        {% for track in metadata %}
                            {% for key, value in track.items() %}
                                <tr>
                                    <td>{{ key }}</td>
                                    <td>{{ value }}</td>
                                </tr>
                            {% endfor %}
                        {% endfor %}
                    {% else %}
                        <tr>
                            <td colspan="2">No metadata available for this file.</td>
                        </tr>
                    {% endif %}
                </tbody>
            </table>
        </div>
    </div>
</div>

<!-- Contenedor para el Toast (puede ir en base.html o aquí) -->
<div class="position-fixed bottom-0 end-0 p-3" style="z-index: 1100">
    <div id="liveToast" class="toast align-items-center text-white bg-primary border-0" role="alert" aria-live="assertive" aria-atomic="true" style="display: none;">
        <div class="d-flex">
            <div class="toast-body">
                <!-- Mensaje dinámico -->
            </div>
            <button type="button" class="btn-close btn-close-white me-2 m-auto" data-bs-dismiss="toast" aria-label="Close"></button>
        </div>
    </div>
</div>

<script>
    function toggleMetadata() {
        const content = document.getElementById("metadata-content");
        if (content.style.display === "none") {
            content.style.display = "block";
        } else {
            content.style.display = "none";
        }
    }

    // Solo configuramos el listener si el usuario está autenticado
    {% if current_user.is_authenticated %}
    document.addEventListener('DOMContentLoaded', () => {
        const favoriteButton = document.getElementById('favorite-button');
        if (favoriteButton) {
            favoriteButton.addEventListener('click', function() {
                fetch(`/paste/{{ paste_id }}/favorite`, {
                    method: 'POST',
                    headers: {
                        'Authorization': 'Bearer {{ token }}' 
                    }
                })
                .then(response => {
                    if (!response.ok) {
                        throw new Error('Failed to toggle favorite');
                    }
                    return response.json();
                })
                .then(data => {
                    const message = data.message || 'Action completed!';
                    showToast(message, 'bg-success');
                })
                .catch(error => {
                    console.error('Error:', error);
                    showToast('Error adding to favorites.', 'bg-danger');
                });
            });
        }
    });

    // Función para mostrar el toast
    function showToast(message, bgColor = 'bg-primary') {
        const toastElement = document.getElementById('liveToast');
        const toastBody = toastElement.querySelector('.toast-body');

        toastBody.textContent = message;
        toastElement.className = `toast align-items-center text-white ${bgColor} border-0`;
        toastElement.style.display = 'block'; // Mostrar el contenedor

        const toast = new bootstrap.Toast(toastElement);
        toast.show();
    }
    {% endif %}
</script>
{% endblock %}
{% block footer %}
  {{ super() }}  <!-- Esto conserva el contenido original del footer definido en base.html -->
{% endblock %}
