<h1 id="photoname">Photo</h1>
<div class="pagebar">
  <a href="/photos">← all photos</a>
  <span id="position"></span>
  <a id="prevlink" hidden>previous</a>
  <a id="nextlink" hidden>next</a>
  <a id="rawlink" target="_blank">open full size</a>
  <span class="keyhelp"><kbd>←</kbd>/<kbd>→</kbd> move between photos</span>
</div>
<div id="photobody"><p class="empty">Loading…</p></div>
<script>
"use strict";
const NAME = decodeURIComponent(location.pathname.split("/").pop());
document.getElementById("photoname").textContent = NAME;
document.getElementById("rawlink").href = `/photos/${encodeURIComponent(NAME)}`;
document.title = `bggpipe — ${NAME}`;

function ticket(s) {
  return `
  <section class="ticket"
           data-photo="${esc(s.photo)}" data-location="${esc(s.location)}"
           data-partial="${esc(s.partial_text)}" data-art="${esc(s.art_notes)}">
    <span class="stencil">reshoot</span>
    <div>
      <div class="loc">${esc(s.location) || "somewhere in this photo"}</div>
      ${s.partial_text ? `<div class="partial">text visible: ${esc(s.partial_text)}</div>` : ""}
      ${s.art_notes ? `<div class="notes">${esc(s.art_notes)}</div>` : ""}
      <button class="dismiss">dismiss — found it / not a game</button>
    </div>
  </section>`;
}

function render(state, photos) {
  const info = photos.find(p => p.name === NAME);
  const body = document.getElementById("photobody");
  if (!info) {
    body.innerHTML = `<p class="empty">No photo named <b>${esc(NAME)}</b> is on file —
      back to <a href="/photos">all photos</a>.</p>`;
    return;
  }

  const ix = photos.findIndex(p => p.name === NAME);
  document.getElementById("position").innerHTML =
    `<b>${ix + 1}</b> of <b>${photos.length}</b>`;
  const prev = photos[ix - 1], next = photos[ix + 1];
  const prevEl = document.getElementById("prevlink");
  const nextEl = document.getElementById("nextlink");
  prevEl.hidden = !prev;
  nextEl.hidden = !next;
  if (prev) prevEl.href = `/photos/view/${encodeURIComponent(prev.name)}`;
  if (next) nextEl.href = `/photos/view/${encodeURIComponent(next.name)}`;

  const titles = state.catalog.filter(c => c.photos.includes(NAME));
  const tickets = state.unidentified.filter(s => s.photo === NAME);

  let html = `
  <a href="/photos/${encodeURIComponent(NAME)}" target="_blank">
    <img class="fullshot" src="/photos/${encodeURIComponent(NAME)}"
         alt="shelf photo ${esc(NAME)}"></a>`;

  html += `<h2>Titles read from this photo <span class="count">— ${titles.length}</span></h2>`;
  html += titles.length
    ? `<div class="catalog"><table>` + titles.map(c => `
      <tr>
        <td class="t">${esc(c.title_raw)}</td>
        <td>${statusChip(c)}</td>
        <td class="meta">${metaLine(c)}</td>
      </tr>`).join("") + `</table></div>`
    : `<p class="empty">${info.extracted
        ? "No titles were read from this photo."
        : "Not extracted yet — run <b>extract</b> from the <a href='/'>pipeline</a>."}</p>`;

  if (tickets.length) {
    html += `<h2>Reshoot tickets <span class="count">— boxes seen here but not identified</span></h2>`;
    html += tickets.map(ticket).join("");
  }
  body.innerHTML = html;

  body.querySelectorAll(".dismiss").forEach(b => b.addEventListener("click", async () => {
    const t = b.closest(".ticket");
    const res = await apiPost("/api/dismiss", {
      photo: t.dataset.photo, location: t.dataset.location,
      partial_text: t.dataset.partial, art_notes: t.dataset.art,
    });
    if (res) refresh().catch(() => {});
  }));
}

let LAST = null;
async function refresh() {
  const [state, photos] = await Promise.all([
    fetchJSON("/api/state"),
    fetchJSON("/api/photos-list"),
  ]);
  const payload = JSON.stringify([state.catalog, state.unidentified, photos]);
  if (payload === LAST) return;
  render(state, photos);
  LAST = payload;  // after render: a throw must not freeze the page as "current"
}

document.addEventListener("keydown", e => {
  if (e.target.tagName === "INPUT") return;
  if (e.key === "ArrowLeft" && !document.getElementById("prevlink").hidden)
    location.href = document.getElementById("prevlink").href;
  if (e.key === "ArrowRight" && !document.getElementById("nextlink").hidden)
    location.href = document.getElementById("nextlink").href;
});

refresh().catch(err => errorBanner(err.message || err));
pollLoop(refresh, 5000, () => showBanner(""));
</script>
