/* tui file browser — preview pane (image OR text panes), hover + freeze +
   keyboard. re-binds itself after pjax navigation (document listeners are added
   once; rows/preview are re-queried per page). */
(function () {
  "use strict";
  var rows = [], img = null, texts = [], cap = null, cur = 0, frozen = false, container = null, player = null, pv = null;

  function hideTexts() { texts.forEach(function (t) { t.hidden = true; }); }
  function showText(k) { texts.forEach(function (t) { t.hidden = (t.getAttribute("data-text") !== k); }); }
  function hidePlayer() { if (player) { player.hidden = true; if (pv && !pv.paused) pv.pause(); } }
  function showPlayer() { if (player) player.hidden = false; }
  function setFrozen(v) { frozen = v; if (container) container.classList.toggle("is-frozen", v); }
  function showImg(src) {
    if (!img) return;
    img.hidden = false;
    if (img.getAttribute("src") === src) { img.style.opacity = "1"; return; }
    img.style.opacity = "0";
    img.onload = img.onerror = function () { img.style.opacity = "1"; };
    img.src = src;
    if (img.complete) img.style.opacity = "1";   // already cached → no fade
  }

  function select(i) {
    if (!rows.length) return;
    if (i < 0) i = 0;
    if (i >= rows.length) i = rows.length - 1;
    cur = i;
    for (var r = 0; r < rows.length; r++) rows[r].classList.remove("is-selected");
    var a = rows[i];
    a.classList.add("is-selected");
    if (a.scrollIntoView) a.scrollIntoView({ block: "nearest" });

    var src = a.getAttribute("data-img");
    var tkey = a.getAttribute("data-text");
    var vid = a.getAttribute("data-video");
    if (src) { showImg(src); hideTexts(); hidePlayer(); }
    else if (vid) { if (img) img.hidden = true; hideTexts(); showPlayer(); }
    else if (tkey) { if (img) img.hidden = true; hidePlayer(); showText(tkey); }
    else { if (img) img.hidden = true; hideTexts(); hidePlayer(); }

    if (cap) {
      var n = a.querySelector(".tui__name");
      var y = a.querySelector(".tui__date");
      cap.textContent = (n ? n.textContent.trim() : a.getAttribute("data-name")) + (y ? "  " + y.textContent.trim() : "");
    }
  }

  function bind() {
    var list = document.querySelector(".filebrowser .tui__ls");
    container = list ? list.closest(".filebrowser") : null;
    rows = list ? Array.prototype.slice.call(list.querySelectorAll("a[data-name]")) : [];
    img = document.querySelector(".tui__preview img");
    texts = Array.prototype.slice.call(document.querySelectorAll(".tui__preview .tui__text"));
    player = document.querySelector(".tui__preview .player");
    pv = player ? player.querySelector("video") : null;
    cap = document.querySelector(".tui__status");
    cur = 0; frozen = false;
    if (!rows.length) return;

    rows.forEach(function (a, i) {
      a.addEventListener("mouseenter", function () { if (!frozen) select(i); });
      a.addEventListener("click", function (e) {
        if (a.getAttribute("href")) return;        // navigation rows behave normally
        e.preventDefault();
        if (frozen && cur === i) setFrozen(false);
        else { select(i); setFrozen(true); }
      });
    });

    var start = rows.findIndex(function (a) { return a.classList.contains("is-selected"); });
    select(start < 0 ? 0 : start);

    // warm the cache so switching between gallery images is instant
    var srcs = rows.map(function (a) { return a.getAttribute("data-img"); }).filter(Boolean);
    if (srcs.length) {
      var preload = function () { srcs.forEach(function (s) { var im = new Image(); im.src = s; }); };
      if (window.requestIdleCallback) requestIdleCallback(preload); else setTimeout(preload, 300);
    }
  }

  // one-time document listeners (reference the current bound state)
  document.addEventListener("click", function (e) {
    if (e.target.closest && e.target.closest(".tui__ls a")) return;
    if (frozen) setFrozen(false);
  });
  document.addEventListener("keydown", function (e) {
    var t = e.target;
    if (t && (t.isContentEditable || /^(input|textarea|select)$/i.test(t.tagName))) return;
    if (!rows.length) return;
    if (e.key === "ArrowDown") { e.preventDefault(); select(cur + 1); }
    else if (e.key === "ArrowUp") { e.preventDefault(); select(cur - 1); }
    else if (e.key === "Enter") {
      var href = rows[cur] && rows[cur].getAttribute("href");
      if (href) { if (window.pjax) window.pjax(href); else window.location.href = href; }
    }
  });

  bind();
  document.addEventListener("pjax:load", bind);
})();
