/**
 * Shared top hero: cycle every image listed in img/pool/images.json.
 * Add a jpg/png/webp to img/pool/ and add its filename to images.json.
 * Same pool on every page.
 */
(function () {
  const LIST_URL = "img/pool/images.json";
  const INTERVAL_MS = 8000;
  const FADE_MS = 1200;

  function stage() {
    let el = document.querySelector(".hero-stage");
    if (el) return el;
    el = document.createElement("div");
    el.className = "hero-stage";
    el.setAttribute("aria-hidden", "true");
    el.innerHTML = '<div class="hero-slide is-on"></div><div class="hero-slide"></div>';
    document.body.insertBefore(el, document.body.firstChild);
    return el;
  }

  function setBg(node, url) {
    node.style.backgroundImage = 'url("' + url + '")';
  }

  fetch(LIST_URL, { cache: "no-store" })
    .then(function (r) { return r.json(); })
    .then(function (files) {
      if (!files || !files.length) return;
      const urls = files.map(function (f) {
        return f.indexOf("/") >= 0 ? f : "img/pool/" + f;
      });
      const slides = stage().querySelectorAll(".hero-slide");
      let i = Math.floor(Math.random() * urls.length);
      let on = 0;
      setBg(slides[0], urls[i]);
      if (urls.length === 1) return;
      setInterval(function () {
        i = (i + 1) % urls.length;
        const next = 1 - on;
        setBg(slides[next], urls[i]);
        slides[next].classList.add("is-on");
        slides[on].classList.remove("is-on");
        on = next;
      }, INTERVAL_MS);
    })
    .catch(function () { /* keep CSS fallback */ });
})();
