{% extends "base_list.html" %}
{% load form_tags %}
{% load mathfilters %}
{% load naturalduration %}
{% load static %}

{% block title %}{{object.name}}{% endblock %}

{% block head_extra %}
    <link rel="stylesheet" href="https://unpkg.com/leaflet@1.9.4/dist/leaflet.css" />
    <style>

        dl { border:none; }
        dt {
            background: #333;
            color: #fff;
        }
        dd {
            float:left;
            margin: 2px;
            padding: 4px;
            min-height: 1em;
            border: none;
        }
        #map {
            height: 400px;
            border-radius: 4px;
        }
        .heart-icon {
            cursor: pointer;
            transition: fill 0.2s, stroke 0.2s;
        }
        .heart-icon.favorited {
            fill: #e74c3c;
            stroke: #e74c3c;
        }
        .heart-icon:not(.favorited) {
            fill: none;
            stroke: #888;
        }
        .heart-icon:not(.favorited):hover {
            stroke: #e74c3c;
        }
        </style>
{% endblock %}

{% block lists %}

<div class="row">

<h1 class="d-flex align-items-center gap-2">
{% if object.media_type == "Video" %}🎬{% elif object.media_type == "Track" %}🎵{% elif object.media_type == "PodcastEpisode" %}🎙️{% elif object.media_type == "SportEvent" %}⚽{% elif object.media_type == "Book" %}📚{% elif object.media_type == "Paper" %}📄{% elif object.media_type == "VideoGame" %}🎮{% elif object.media_type == "BoardGame" %}🎲{% elif object.media_type == "GeoLocation" %}📍{% elif object.media_type == "Trail" %}🥾{% elif object.media_type == "Beer" %}🍺{% elif object.media_type == "Puzzle" %}🧩{% elif object.media_type == "Food" %}🍔{% elif object.media_type == "Task" %}✅{% elif object.media_type == "WebPage" %}🌐{% elif object.media_type == "LifeEvent" %}🎉{% elif object.media_type == "Mood" %}😊{% elif object.media_type == "BrickSet" %}🧱{% elif object.media_type == "Channel" %}📺{% elif object.media_type == "AgentSession" %}🤖{% elif object.media_type == "Workout" %}🏋️{% endif %}
{% if object.media_obj.get_absolute_url %}
    <a href="{{ object.media_obj.get_absolute_url }}">{% endif %}
        {{ object.media_obj.title }}
        {% if object.media_obj.get_absolute_url %}</a>
        {% endif %}
{% if user.is_authenticated and object.media_obj and object.media_type != "AgentSession" %}
<button id="favorite-btn"
  data-url="{% url 'scrobbles:toggle-favorite' object.media_type object.media_obj.id %}"
  data-favorited="{{ is_favorited|yesno:'true,false' }}"
  class="btn btn-sm p-0 border-0 bg-transparent">
  <svg width="20" height="20" viewBox="0 0 24 24" class="heart-icon{% if is_favorited %} favorited{% endif %}" id="heart-svg">
    <path d="M12 21.35l-1.45-1.32C5.4 15.36 2 12.28 2 8.5 2 5.42 4.42 3 7.5 3c1.74 0 3.41.81 4.5 2.09C13.09 3.81 14.76 3 16.5 3 19.58 3 22 5.42 22 8.5c0 3.78-3.4 6.86-8.55 11.54L12 21.35z"/>
  </svg>
</button>
{% endif %}
</h1>
<h2>{{ object.media_obj.subtitle }}</h2>
<p>
{% if object.media_type == "SportEvent" %}
{% for team in object.media_obj.teams.all %}
<img src="{{team.logo.url}}" width=150 />
{% endfor %}
{% endif %}
{% if object.media_type == "Task" and object.logdata.title %}
    </p>
<h2>{{ object.logdata.title }}</h2>
{% endif %}
{% if object.media_type == "AgentSession" and object.logdata.title %}
    </p>
<h2>{{ object.logdata.title }}</h2>
{% endif %}
<h3 class="text-muted">{{ object.local_timestamp }}</h3>

{% if user.is_authenticated and object.user == user %}
<div class="mb-3 d-flex align-items-center gap-2 flex-wrap">
    <span class="badge 
        {% if object.visibility == 'public' %}bg-success
        {% elif object.visibility == 'shared' %}bg-warning text-dark
        {% else %}bg-secondary
        {% endif %}">
        {{ object.get_visibility_display }}
    </span>
    <form method="post" action="{% url 'scrobbles:change-visibility' object.id %}" class="d-inline-flex align-items-center gap-1">
        {% csrf_token %}
        <select name="visibility" class="form-select form-select-sm" style="width:auto;" onchange="this.form.submit()">
            <option value="private" {% if object.visibility == 'private' %}selected{% endif %}>Private</option>
            <option value="shared" {% if object.visibility == 'shared' %}selected{% endif %}>Shared (link)</option>
            <option value="public" {% if object.visibility == 'public' %}selected{% endif %}>Public (explore)</option>
        </select>
    </form>
    {% if object.visibility == 'shared' and object.get_share_url %}
    <span class="small text-muted">Share link:</span>
    <code class="small" id="share-link">{{ request.scheme }}://{{ request.get_host }}{{ object.get_share_url }}</code>
    <button class="btn btn-sm btn-outline-secondary" onclick="navigator.clipboard.writeText(document.getElementById('share-link').textContent.trim())">Copy</button>
    <form method="post" action="{% url 'scrobbles:regenerate-share-token' object.id %}" class="d-inline">
        {% csrf_token %}
        <button type="submit" class="btn btn-sm btn-outline-warning">Regenerate</button>
    </form>
    {% if object.share_view_count %}
    <span class="text-muted small ms-2">{{ object.share_view_count }} view{{ object.share_view_count|pluralize }}</span>
    {% endif %}
    <a href="{% url 'scrobbles:share-analytics' object.id %}" class="btn btn-sm btn-outline-info ms-2">Analytics</a>
    {% endif %}
</div>
{% endif %}

{% if user.is_authenticated and object.media_type == "Track" and has_mopidy_uri and user.profile.mopidy_api_url %}
<form method="post" action="{% url 'scrobbles:add-to-mopidy-queue' object.id %}" class="mb-1">
  {% csrf_token %}
    <button type="submit" class="btn btn-sm btn-outline-secondary">add to mopidy queue</button>
</form>
{% if user.profile.monthly_mopidy_playlist_pattern %}
<form method="post" action="{% url 'scrobbles:add-to-mopidy-monthly-playlist' object.id %}" class="mb-1">
  {% csrf_token %}
    <button type="submit" class="btn btn-sm btn-outline-secondary">add to monthly playlist</button>
</form>
{% endif %}
{% endif %}
{% if object.media_type == "Track" %}
<p class="text-muted small">Source: {{ object.source }}{% if object.log.mopidy_source %} ({{ object.log.mopidy_source|capfirst }}){% endif %}</p>
{% endif %}
{% if object.media_type == "Task" and object.log.weight %}
<div class="mb-3">
  <dl class="row" style="max-width: 400px;">
    <dt class="col-sm-5">Weight</dt>
    <dd class="col-sm-7">{{ object.log.weight }} {% if object.log.unit_type == "imperial" %}lbs{% else %}kg{% endif %}</dd>
    {% if object.log.body_fat %}
    <dt class="col-sm-5">Body Fat</dt>
    <dd class="col-sm-7">{{ object.log.body_fat }}%</dd>
    {% endif %}
    {% if object.log.bmi %}
    <dt class="col-sm-5">BMI</dt>
    <dd class="col-sm-7">{{ object.log.bmi }}</dd>
    {% endif %}
    {% if object.log.muscle %}
    <dt class="col-sm-5">Muscle</dt>
    <dd class="col-sm-7">{{ object.log.muscle }} {% if object.log.unit_type == "imperial" %}lbs{% else %}kg{% endif %}</dd>
    {% endif %}
    {% if object.log.bone %}
    <dt class="col-sm-5">Bone</dt>
    <dd class="col-sm-7">{{ object.log.bone }} {% if object.log.unit_type == "imperial" %}lbs{% else %}kg{% endif %}</dd>
    {% endif %}
    {% if object.log.water %}
    <dt class="col-sm-5">Water</dt>
    <dd class="col-sm-7">{{ object.log.water }}%</dd>
    {% endif %}
    {% if object.log.visceral_fat %}
    <dt class="col-sm-5">Visceral Fat</dt>
    <dd class="col-sm-7">{{ object.log.visceral_fat }}</dd>
    {% endif %}
    {% if object.log.waist %}
    <dt class="col-sm-5">Waist</dt>
    <dd class="col-sm-7">{{ object.log.waist }} {% if object.log.unit_type == "imperial" %}in{% else %}cm{% endif %}</dd>
    {% endif %}
    {% if object.log.lbm %}
    <dt class="col-sm-5">Lean Mass</dt>
    <dd class="col-sm-7">{{ object.log.lbm }} {% if object.log.unit_type == "imperial" %}lbs{% else %}kg{% endif %}</dd>
    {% endif %}
    {% if object.log.calories %}
    <dt class="col-sm-5">Calories</dt>
    <dd class="col-sm-7">{{ object.log.calories }}</dd>
    {% endif %}
    {% if object.log.comment %}
    <dt class="col-sm-5">Comment</dt>
    <dd class="col-sm-7">{{ object.log.comment }}</dd>
    {% endif %}
  </dl>
</div>
{% endif %}
{% if object.media_type == "Beer" or object.media_type == "Wine" or object.media_type == "Coffee" %}
{% if object.logdata.format_display or object.logdata.size_ml %}
<div class="mb-3">
  <dl class="row" style="max-width: 400px;">
    {% if object.logdata.format_display %}
    <dt class="col-sm-5">Format</dt>
    <dd class="col-sm-7">{{ object.logdata.format_display }}</dd>
    {% endif %}
    {% if object.logdata.size_ml %}
    <dt class="col-sm-5">Size</dt>
    <dd class="col-sm-7">
        {% if user.is_authenticated and request.user.profile.volume_unit == "imperial" %}
            {{ object.logdata.size_oz }} oz
        {% else %}
            {{ object.logdata.size_ml }} mL
        {% endif %}
    </dd>
    {% endif %}
    {% if object.logdata.roast_level_display %}
    <dt class="col-sm-5">Roast</dt>
    <dd class="col-sm-7">{{ object.logdata.roast_level_display }}</dd>
    {% endif %}
    {% if object.logdata.brewing_method_display %}
    <dt class="col-sm-5">Method</dt>
    <dd class="col-sm-7">{{ object.logdata.brewing_method_display }}</dd>
    {% endif %}
  </dl>
</div>
{% endif %}
{% endif %}
{% if object.media_type == "Task" and object.logdata.description %}
<p>{{ object.logdata.description }}</p>
{% endif %}

{% if object.media_type == "Trail" and object.gpx_file %}
<div class="mb-3">
    <div id="map"></div>
</div>
{% endif %}

{% if object.screenshot %}
<div class="mb-3">
    <img src="{{ object.screenshot_large.url }}" class="img-fluid rounded" style="max-height: 600px;" alt="Screenshot" />
</div>
{% endif %}

<p>
    Tags: 
    {% if object.tags.all %}
    {% for tag in object.tags.all %}
        <a href="{% url 'scrobbles:scrobble-list' %}?tags={{ tag.name }}" class="badge bg-secondary">{{ tag.name }}</a>
    {% endfor %}
    {% else %}
    untagged
    {% endif %}
</p>

{% with notes_html=object.logdata.notes_as_html %}
{% if notes_html %}
<div class="mb-3">
  <h4>Notes</h4>
  <span class="badge fs-8
      {% if sentiment.compound >= 0.5 %}bg-success
      {% elif sentiment.compound >= 0.05 %}bg-info text-dark
      {% elif sentiment.compound > -0.05 %}bg-secondary
      {% elif sentiment.compound > -0.5 %}bg-warning text-dark
      {% else %}bg-danger
      {% endif %}">
      {% if sentiment.compound >= 0.5 %}Positive
      {% elif sentiment.compound >= 0.05 %}Slightly positive
      {% elif sentiment.compound > -0.05 %}Neutral
      {% elif sentiment.compound > -0.5 %}Slightly negative
      {% else %}Negative
      {% endif %}
  </span>
  <div class="notes-list">
    {{ notes_html|safe }}
  </div>
</div>
{% endif %}
{% endwith %}

{% with sentiment=object.log.sentiment %}
{% if sentiment %}
<div class="mb-3">
</div>
{% endif %}
{% endwith %}

{% if object.logdata.avg_seconds_per_page %}
<p>Rate: {{object.logdata.avg_seconds_per_page}}s per page</p>
{% endif %}

{% if object.media_type == "BoardGame" and object.logdata.as_html %}
<div class="mb-3">
  <h5>Game Details</h5>
  {{ object.logdata.as_html|safe }}
</div>
{% endif %}

{% if object.media_type == "Workout" and object.logdata.workouts %}
<div class="mb-3">
  <h5>Workout Details</h5>
  {% if user.is_authenticated %}
  {{ object.logdata|workout_html:request.user.profile.weigh_in_units|safe }}
  {% else %}
  {{ object.logdata|workout_html:"metric"|safe }}
  {% endif %}
</div>
{% endif %}

{% if object.media_type == "AgentSession" %}
<div class="mb-3">
  {% include "scrobbles/_agent_session.html" %}
</div>
{% endif %}

{% if user.is_authenticated and object.user == user %}
<button class="btn btn-secondary mb-3" type="button" data-bs-toggle="collapse" data-bs-target="#editLogForm">
  Edit Log
</button>
<div class="collapse mb-3" id="editLogForm">
  <form method="post" class="needs-validation mt-3" novalidate>
    {% csrf_token %}
    {% for field in log_form %}
      <div class="mb-3">
        <label for="{{ field.id_for_label }}" class="form-label">{{ field.label }}</label>
        {{ field|add_class:"form-control" }}
        {% if field.help_text %}
          <div class="form-text">{{ field.help_text }}</div>
        {% endif %}
        {% for error in field.errors %}
          <div class="invalid-feedback d-block">{{ error }}</div>
        {% endfor %}
      </div>
    {% endfor %}

    <button type="submit" class="btn btn-primary">Save</button>
  </form>
</div>
{% endif %}

<h2 class="mt-4">All scrobbles of this {{ object.media_type|lower }}</h2>
{% if related_scrobbles %}
<p class="text-muted">
    {{ related_scrobbles.paginator.count }} scrobble{{ related_scrobbles.paginator.count|pluralize }}
    {% if object.is_long_play and long_play_total_seconds %}
    | Total time: {{ long_play_total_seconds|natural_duration }}
    {% if long_play_finished_date %} | Finished: {{ long_play_finished_date|date:"M d, Y" }}{% endif %}
    {% endif %}
</p>
<table class="table table-striped table-sm">
    <thead>
        <tr>
            <th scope="col">Date</th>
            <th scope="col">Title</th>
            <th scope="col">Time</th>
        </tr>
    </thead>
    <tbody>
        {% for scrobble in related_scrobbles %}
        <tr{% if scrobble.id == object.id %} class="table-active fw-bold"{% endif %}>
            <td>{% if scrobble.id == object.id %}{{ scrobble.timestamp|date:"M d, Y" }}{% else %}<a href="{% url 'scrobbles:detail' scrobble.id %}">{{ scrobble.timestamp|date:"M d, Y" }}</a>{% endif %}</td>
            <td>
                {% if scrobble.media_type == "Task" and scrobble.logdata.title %}{{ scrobble.media_obj.title }}: {{ scrobble.logdata.title }}{% elif scrobble.media_type == "AgentSession" and scrobble.logdata.title %}{{ scrobble.logdata.title }}{% else %}{{ scrobble.media_obj.title|default:scrobble.media_obj }}{% endif %}
            </td>
            <td>
                {% if scrobble.is_long_play and scrobble.long_play_seconds %}
                    {{ scrobble.playback_position_seconds|natural_duration }} ({{ scrobble.long_play_seconds|natural_duration }} total)
                {% elif scrobble.playback_position_seconds %}
                    {{ scrobble.playback_position_seconds|natural_duration }}
                {% endif %}
            </td>
        </tr>
        {% endfor %}
    </tbody>
</table>

{% if related_scrobbles.has_other_pages %}
<nav>
    <ul class="pagination">
        {% if related_scrobbles.has_previous %}
        <li class="page-item"><a class="page-link" href="?page={{ related_scrobbles.previous_page_number }}">Previous</a></li>
        {% else %}
        <li class="page-item disabled"><span class="page-link">Previous</span></li>
        {% endif %}

        {% for num in related_scrobbles.paginator.page_range %}
            {% if related_scrobbles.number == num %}
            <li class="page-item active"><span class="page-link">{{ num }}</span></li>
            {% elif num > related_scrobbles.number|add:'-3' and num < related_scrobbles.number|add:'3' %}
            <li class="page-item"><a class="page-link" href="?page={{ num }}">{{ num }}</a></li>
            {% endif %}
        {% endfor %}

        {% if related_scrobbles.has_next %}
        <li class="page-item"><a class="page-link" href="?page={{ related_scrobbles.next_page_number }}">Next</a></li>
        {% else %}
        <li class="page-item disabled"><span class="page-link">Next</span></li>
        {% endif %}
    </ul>
</nav>
{% endif %}

{% else %}
<p class="text-muted">No other scrobbles of this media.</p>
{% endif %}

</div>

{% endblock %}

{% block extra_js %}
{{ block.super }}
{% if user.is_authenticated and object.user == user %}{{ log_form.media }}{% endif %}
<script>
function getCookie(name) {
    let value = "; " + document.cookie;
    let parts = value.split("; " + name + "=");
    if (parts.length === 2) return parts.pop().split(";").shift();
}
document.getElementById("favorite-btn")?.addEventListener("click", function() {
    var btn = this;
    var url = btn.dataset.url;
    fetch(url, {
        method: "POST",
        headers: {
            "X-CSRFToken": getCookie("csrftoken"),
            "X-Requested-With": "XMLHttpRequest",
        },
    })
    .then(function(r) { return r.json(); })
    .then(function(data) {
        var heart = document.getElementById("heart-svg");
        btn.dataset.favorited = data.is_favorited ? "true" : "false";
        heart.classList.toggle("favorited", data.is_favorited);
    });
});
</script>
{% if object.media_type == "Trail" and object.gpx_file %}
<script src="https://unpkg.com/leaflet@1.9.4/dist/leaflet.js"></script>
<script src="https://cdn.jsdelivr.net/npm/leaflet-gpx@2.2.0/gpx.min.js"></script>
<script>
var map = L.map('map');
L.tileLayer('https://tile.openstreetmap.org/{z}/{x}/{y}.png', {
    maxZoom: 19,
    attribution: '&copy; <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a>',
    referrerPolicy: 'origin'
}).addTo(map);
var gpx = new L.GPX("{{ object.gpx_file.url|escapejs }}", {
    async: true,
    polyline_options: { color: '#e74c3c' }
});
gpx.on('loaded', function(e) {
    map.fitBounds(e.target.getBounds());
});
gpx.addTo(map);
</script>
{% endif %}
{% endblock %}
