{% extends "base.html" %}
{% set load_tui_editor = true %}

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

{% block content %}
<style>
#tui-image-editor {
    width: 100%;
    height: 800px;  /* Se aumenta la altura vertical */
    border: 1px solid #ccc;
    background-color: #2d2d2d;
}

.tui-image-editor-container {
    border-radius: 10px;
    overflow: hidden;
}

.tui-image-editor-header {
    display: none;
}
</style>

<body data-theme="{{ session.get('theme', 'light') }}"
      data-paste-id="{{ paste_id if paste_id else '' }}"
      data-download-url="{{ url_for('download_paste', id=paste_id, _external=True) }}">

<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 id="original-image" 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 flex-wrap justify-content-center gap-2 mt-4">
    <button class="btn btn-primary" onclick="toggleMetadata()" title="Toggle Metadata">
        <i class="fas fa-info-circle"></i>
    </button>
    <a href="{{ url_for('download_paste', id=paste_id) }}" class="btn btn-primary" title="Download">
        <i class="fas fa-download"></i>
    </a>
    <a href="{{ url_for('get_file', filename=filename) }}" class="btn btn-primary" target="_blank" title="View Raw">
        <i class="fas fa-external-link-alt"></i>
    </a>
    <button id="copy-url-button" class="btn btn-sm btn-secondary" title="Copy URL">
      <i class="fas fa-link"></i>
    </button>

    {% if current_user.is_authenticated %}
        <button id="favorite-button" class="btn btn-primary text-light" title="Add to Favorites">
            <i class="fas fa-heart"></i>
        </button>
    {% endif %}

    {% if mime_type.startswith("image/") and can_edit and has_gps %}
    <button id="gps-button" class="btn btn-primary" onclick="removeGPSMetadata({{ paste_id }})" title="Remove GPS Data">
        <i class="fas fa-map-marker-alt"></i>
    </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() %}
                            {% if key == "GPS Data" and value.get("Decimal Coordinates") %}
                                <tr>
                                    <td>{{ key }}</td>
                                    <td>
                                        <span id="gps-coordinates"
                                              data-lat="{{ value['Decimal Coordinates'].split(',')[0]|trim }}"
                                              data-lon="{{ value['Decimal Coordinates'].split(',')[1]|trim }}">
                                            {{ value['Decimal Coordinates'] }}
                                        </span>
                                    </td>
                                </tr>
                            {% else %}
                                <tr>
                                    <td>{{ key }}</td>
                                    <td>{{ value }}</td>
                                </tr>
                            {% endif %}
                        {% endfor %}
                    {% endfor %}
                {% endif %}
            </tbody>
        </table>
    </div>
</div>

{% if metadata %}
    {% for track in metadata %}
        {% for key, value in track.items() %}
            {% if key == "GPS Data" and value.get("Decimal Coordinates") %}
                <h3 class="mt-4">📍 Location Preview</h3>
                <div id="map" style="width: 100%; height: 400px; border-radius: 8px;"></div>

                <script>
                    window.addEventListener("load", function() {
                        if (typeof L === "undefined") {
                            console.error("❌ Leaflet.js no se ha cargado correctamente.");
                            return;
                        }

                        var gpsElement = document.getElementById("gps-coordinates");
                        if (!gpsElement) {
                            console.error("❌ No se encontraron coordenadas GPS en la página.");
                            return;
                        }

                        var lat = parseFloat(gpsElement.dataset.lat);
                        var lon = parseFloat(gpsElement.dataset.lon);

                        var map = L.map('map').setView([lat, lon], 15);

                        L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
                            attribution: '© OpenStreetMap contributors'
                        }).addTo(map);

                        L.marker([lat, lon])
                            .addTo(map)
                            .bindPopup("📍 Image Location")
                            .openPopup();
                    });
                </script>
            {% endif %}
        {% endfor %}
    {% endfor %}
{% endif %}

{% if mime_type.startswith("image/") and can_edit %}
    <div class="text-center mt-4">
        <button class="btn btn-success" onclick="enableEditor('{{ url_for('get_file', filename=filename) }}', '{{ filename }}')" title="Edit Image">
            <i class="fas fa-paint-brush"></i>
        </button>

        <div id="image-editor-container" style="display: none;">
            <div id="tui-image-editor" style="max-width: 800px; margin: auto;"></div>
            <button class="btn btn-primary mt-2" onclick="saveEditedImage({{ paste_id }})" title="Save Image">
                <i class="fas fa-save"></i>
            </button>
        </div>
    </div>
{% endif %}

{% endblock %}

{% block scripts %}
<script>
    window.FLASK_VARS = {
        pasteId: {{ paste_id }},
        saveImageUrl: "{{ url_for('save_edited_image', paste_id=paste_id) }}",
        getFileUrl: "{{ url_for('get_file', filename=filename) }}"
    };
</script>
{{ super() }}
    <script src="{{ url_for('static', filename='js/metadata-toggle.js') }}" defer></script>
{% endblock %}

{% block footer %}
  {{ super() }}
{% endblock %}

