{% extends "pages/base.html" %}
{% load i18n %}

{% block title %}{{ stream.name }} | {% trans "MJPEG Debug" %}{% endblock %}

{% block content %}
<div class="container py-5">
  <div class="d-flex flex-wrap align-items-center justify-content-between gap-3 mb-4">
    <div>
      <p class="text-muted mb-1">{% trans "Admin-only MJPEG debug" %}</p>
      <h1 class="h3 mb-0">{{ stream.name }}</h1>
    </div>
    <div class="btn-group" role="group">
      <a class="btn btn-outline-secondary" href="{{ stream.get_absolute_url }}">
        {% trans "Public view" %}
      </a>
      <a class="btn btn-outline-primary" href="{{ stream.get_admin_url }}">
        {% trans "Configure" %}
      </a>
    </div>
  </div>

  <div class="row g-4">
    <div class="col-lg-8">
      <div class="ratio ratio-16x9 bg-dark rounded shadow-sm overflow-hidden">
        <img
          id="debug-stream"
          src="{{ debug_stream_url }}"
          class="img-fluid w-100 h-100 object-fit-cover"
          alt="{% trans 'Live MJPEG stream' %}"
        >
      </div>
      <p class="mt-3 text-muted mb-0">
        {% trans "This view streams the MJPEG feed directly and logs player events, probes, and status checks for troubleshooting." %}
      </p>
    </div>
    <div class="col-lg-4">
      <div class="card shadow-sm h-100">
        <div class="card-body d-flex flex-column">
          <div class="d-flex flex-wrap gap-2 mb-3">
            <button class="btn btn-sm btn-outline-primary" type="button" id="debug-probe">
              {% trans "Send probe" %}
            </button>
            <button class="btn btn-sm btn-outline-secondary" type="button" id="debug-clear">
              {% trans "Clear log" %}
            </button>
          </div>
          <div class="border rounded p-2 bg-light flex-grow-1 overflow-auto" style="min-height: 220px;">
            <ul class="list-unstyled small mb-0" id="debug-log"></ul>
          </div>
          <div class="mt-3">
            <h2 class="h6 text-muted text-uppercase">{% trans "Latest status" %}</h2>
            <pre class="small mb-0" id="debug-status">{% trans "Waiting for status..." %}</pre>
          </div>
        </div>
      </div>
    </div>
  </div>
</div>
<script>
  (() => {
    const logContainer = document.getElementById("debug-log");
    const statusContainer = document.getElementById("debug-status");
    const streamImage = document.getElementById("debug-stream");
    const probeButton = document.getElementById("debug-probe");
    const clearButton = document.getElementById("debug-clear");
    const statusUrl = "{{ status_url }}";
    const probeUrl = "{{ probe_url }}";

    const appendLog = (level, message, details) => {
      if (!logContainer) {
        return;
      }
      const timestamp = new Date().toLocaleTimeString();
      const entry = document.createElement("li");
      const detailText = details ? ` | ${details}` : "";
      entry.textContent = `[${timestamp}] ${level}: ${message}${detailText}`;
      logContainer.prepend(entry);
    };

    const updateStatus = async () => {
      if (!statusUrl) {
        return;
      }
      try {
        const response = await fetch(statusUrl, { cache: "no-store" });
        if (!response.ok) {
          appendLog("WARN", "Status check failed", `HTTP ${response.status}`);
          return;
        }
        const payload = await response.json();
        if (statusContainer) {
          statusContainer.textContent = JSON.stringify(payload, null, 2);
        }
        appendLog("INFO", "Status updated");
      } catch (error) {
        appendLog("ERROR", "Status check error", error.message);
      }
    };

    const sendProbe = async () => {
      if (!probeUrl) {
        return;
      }
      try {
        const response = await fetch(probeUrl, { cache: "no-store" });
        appendLog("INFO", "Probe sent", `HTTP ${response.status}`);
      } catch (error) {
        appendLog("ERROR", "Probe failed", error.message);
      }
    };

    if (streamImage) {
      streamImage.addEventListener("load", () => {
        appendLog("INFO", "Stream image loaded");
      });
      streamImage.addEventListener("error", () => {
        appendLog("ERROR", "Stream image error");
      });
    }

    if (probeButton) {
      probeButton.addEventListener("click", () => {
        sendProbe();
      });
    }

    if (clearButton) {
      clearButton.addEventListener("click", () => {
        if (logContainer) {
          logContainer.innerHTML = "";
        }
      });
    }

    appendLog("INFO", "Debug session started");
    updateStatus();
    sendProbe();
    const statusInterval = window.setInterval(updateStatus, 10000);
    const probeInterval = window.setInterval(sendProbe, 15000);

    window.addEventListener("beforeunload", () => {
      clearInterval(statusInterval);
      clearInterval(probeInterval);
    });
  })();
</script>
{% endblock %}
