const grid = document.getElementById("grid");

function createTile(artikel) {
  const tile = document.createElement("div");
  tile.className = "tile";

  const img = document.createElement("img");
  img.src = artikel.image;
  img.alt = artikel.title || "Artikelbild";
  tile.appendChild(img);

  const overlay = document.createElement("div");
  overlay.className = "overlay";

  const title = document.createElement("h3");
  title.textContent = artikel.title || "Ohne Titel";
  overlay.appendChild(title);

  tile.appendChild(overlay);

  tile.addEventListener("click", () => tile.classList.toggle("open"));
  return tile;
}

async function ladeGalerie() {
  grid.innerHTML = "";
  let foundAny = false;

  try {
    const res = await fetch("/api/images", {
      headers: { "Accept": "application/x-ndjson" }
    });

    if (!res.ok) throw new Error(`HTTP ${res.status}`);
    if (!res.body) throw new Error("Streaming nicht unterstützt");

    const reader = res.body.getReader();
    const decoder = new TextDecoder("utf-8");
    let buffer = "";

    while (true) {
      const { value, done } = await reader.read();
      if (done) break;

      buffer += decoder.decode(value, { stream: true });

      const lines = buffer.split("\n");
      buffer = lines.pop() ?? "";

      for (const line of lines) {
        const s = line.trim();
        if (!s) continue;

        let artikel;
        try {
          artikel = JSON.parse(s);
        } catch {
          continue;
        }

        if (artikel?.image) {
          grid.appendChild(createTile(artikel));
          foundAny = true;
        }
      }
    }

    // Rest verarbeiten
    const last = buffer.trim();
    if (last) {
      try {
        const artikel = JSON.parse(last);
        if (artikel?.image) {
          grid.appendChild(createTile(artikel));
          foundAny = true;
        }
      } catch {}
    }

    if (!foundAny) {
      grid.innerHTML = '<div class="empty">Keine Bilder gefunden.</div>';
    }

  } catch (err) {
    console.error(err);
    grid.innerHTML = '<div class="empty">Fehler beim Laden der Galerie.</div>';
  }
}

ladeGalerie();