const AgamottoHelpers = (function() {
  const TARGET_PAGE = (typeof window.TARGET_PAGE !== "undefined") ? Number(window.TARGET_PAGE) : 2;
  const DEBUG = false;
  const log = (...args) => DEBUG && console.log("%c[Agamotto]", "color:#06f", ...args);
  const err = (...args) => console.error("%c[Agamotto ERROR]", "color:red;font-weight:bold", ...args);

  const reloadPagesKey = "agamottoReloadedPages";
  const exitTsKey = "agamottoExitedFullscreenAt";
  const exitFromKey = "agamottoExitedFromPageKey";
  const exitHandledKey = "agamottoExitHandledPages";

  // Common keys used also by Online
  const POST_FULLSCREEN_FLAG = "agamottoPostFullscreenReload";
  const POST_FULLSCREEN_LOCK = "agamottoPostFullscreenLock";

  const reloadDonePages = new Set(JSON.parse(sessionStorage.getItem(reloadPagesKey) || "[]"));
  const exitHandledPages = new Set(JSON.parse(sessionStorage.getItem(exitHandledKey) || "[]"));
  const softReloadDone = new Set();

  let lastFullscreenState = !!document.fullscreenElement;
  let lastPageKey = location.pathname + location.hash;
  let cachedAgamottoEl = null;

  function updateCachedAgamotto() {
    try {
      const currentEl = document.querySelector(".h5p-agamotto");
      if (currentEl !== cachedAgamottoEl) cachedAgamottoEl = currentEl;
      return cachedAgamottoEl;
    } catch (e) { err("updateCachedAgamotto", e); return null; }
  }

  function agamottoElement() { return updateCachedAgamotto(); }
  function getPageKey() { return location.pathname + location.hash; }

  function getCurrentPageNumber() {
    try {
      const el = document.querySelector(".h5p-interactive-book-status-progressbar-front");
      if (!el) return null;
      const title = el.getAttribute("title") || "";
      const m = title.match(/^Σελίδα\s+(\d+)/);
      return m ? parseInt(m[1], 10) : null;
    } catch (e) { err("getCurrentPageNumber", e); return null; }
  }

  function agamottoVisible() {
    try {
      const el = agamottoElement();
      if (!el) return false;
      const r = el.getBoundingClientRect();
      return r.width > 0 && r.height > 0;
    } catch (e) { err("agamottoVisible", e); return false; }
  }

  function restoreScrollbars() {
    try {
      document.documentElement.style.overflow = "auto";
      document.body.style.overflow = "auto";
      [".h5p-content", ".h5p-wrapper", ".h5p-iframe", ".h5p-standalone", ".h5p-contents"]
        .forEach(sel => document.querySelectorAll(sel)
          .forEach(node => { node.style.overflow = "auto"; }));
    } catch (e) { err("restoreScrollbars", e); }
  }

  function softReloadAgamotto() {
    try {
      const el = agamottoElement();
      if (!el) return false;
      const prevVis = el.style.visibility;
      el.style.visibility = "hidden";
      restoreScrollbars();
      void el.offsetHeight;

      requestAnimationFrame(() => {
        el.style.visibility = prevVis || "";
        setTimeout(() => {
          restoreScrollbars();
          window.dispatchEvent(new Event("resize"));
          el.dispatchEvent(new Event("scroll"));
        }, 150);
      });
      return true;
    } catch (e) { err("softReloadAgamotto", e); return false; }
  }

  function reloadPage(delay = 150) { setTimeout(() => location.reload(), delay); }

  return {
    TARGET_PAGE,
    POST_FULLSCREEN_FLAG,
    POST_FULLSCREEN_LOCK,
    reloadDonePages,
    exitHandledPages,
    softReloadDone,
    lastFullscreenState,
    lastPageKey,
    cachedAgamottoEl,
    updateCachedAgamotto,
    agamottoElement,
    getPageKey,
    getCurrentPageNumber,
    agamottoVisible,
    restoreScrollbars,
    softReloadAgamotto,
    reloadPage
  };
})();

// ================= Local Script =================
(function() {
  const h = AgamottoHelpers;

  function performReload(type = "unknown") {
    const page = h.getCurrentPageNumber();
    const pageKey = h.getPageKey();
    const fs = !!document.fullscreenElement;

    if (page !== h.TARGET_PAGE) return;
    if (!h.agamottoVisible()) return;

    if (type === "post-fullscreen") {
      h.restoreScrollbars();
      h.reloadDonePages.delete(pageKey);
      sessionStorage.setItem("agamottoReloadedPages", JSON.stringify([...h.reloadDonePages]));
      sessionStorage.setItem(h.POST_FULLSCREEN_LOCK, "1");
      h.reloadPage(400);
      return;
    }

    if (!fs && !h.reloadDonePages.has(pageKey) && !sessionStorage.getItem(h.POST_FULLSCREEN_LOCK)) {
      h.reloadDonePages.add(pageKey);
      sessionStorage.setItem("agamottoReloadedPages", JSON.stringify([...h.reloadDonePages]));
      h.reloadPage(200);
      return;
    }

    if (fs && !h.softReloadDone.has(pageKey)) {
      h.softReloadDone.add(pageKey);
      h.softReloadAgamotto();
    }
  }

  function checkPage() {
    const page = h.getCurrentPageNumber();
    const pageKey = h.getPageKey();
    const fs = !!document.fullscreenElement;
    if (!page) return;

    const pendingPostFullscreen = sessionStorage.getItem(h.POST_FULLSCREEN_FLAG);

    if (!fs && h.lastFullscreenState && !pendingPostFullscreen) {
      sessionStorage.setItem("agamottoExitedFullscreenAt", Date.now());
      sessionStorage.setItem("agamottoExitedFromPageKey", h.lastPageKey);
      sessionStorage.setItem(h.POST_FULLSCREEN_FLAG, "1");
    }

    const ts = sessionStorage.getItem("agamottoExitedFullscreenAt");

    if (ts && page === h.TARGET_PAGE && !fs) {
      sessionStorage.removeItem("agamottoExitedFullscreenAt");
      sessionStorage.removeItem("agamottoExitedFromPageKey");
      sessionStorage.removeItem(h.POST_FULLSCREEN_FLAG);
      sessionStorage.removeItem(h.POST_FULLSCREEN_LOCK);
      performReload("post-fullscreen");
      return;
    }

    if (page === h.TARGET_PAGE && !fs && !h.reloadDonePages.has(pageKey) && !sessionStorage.getItem(h.POST_FULLSCREEN_LOCK)) {
      performReload("normal");
      return;
    }

    if (page === h.TARGET_PAGE && fs && !h.softReloadDone.has(pageKey)) {
      performReload("soft-fullscreen");
      return;
    }

    h.lastFullscreenState = fs;
    h.lastPageKey = pageKey;
  }

  document.addEventListener("fullscreenchange", () => {
    const fs = !!document.fullscreenElement;
    h.lastFullscreenState = fs;
    if (!fs) h.restoreScrollbars();
    setTimeout(checkPage, 200);
  });

  window.addEventListener("hashchange", () => setTimeout(checkPage, 700));
  window.addEventListener("load", () => setTimeout(checkPage, 700));
  setInterval(checkPage, 900);
})();

// ================= Online Script =================
(function() {
  const h = AgamottoHelpers;

  // Use helpers' TARGET_PAGE instead of redefining
  const EXIT_FLAG = h.POST_FULLSCREEN_FLAG;
  const EXIT_LOCK = h.POST_FULLSCREEN_LOCK;
  const EXIT_PAGE = "agamottoFsExitPage"; // unique to online behavior

  // Local-style page detection kept intact
  function getCurrentPage() {
    const el = document.querySelector(".h5p-interactive-book-status-progressbar-front");
    if (!el) return null;
    const title = el.getAttribute("title") || "";
    const m = title.match(/^Σελίδα\s+(\d+)/);
    return m ? parseInt(m[1], 10) : null;
  }

  function startTargetPageWatcher() {
    if (window.__agamottoOnlineWatcherRunning) return;
    window.__agamottoOnlineWatcherRunning = true;

    const watcher = setInterval(() => {
      const flag = sessionStorage.getItem(EXIT_FLAG);
      if (!flag) {
        clearInterval(watcher);
        window.__agamottoOnlineWatcherRunning = false;
        return;
      }

      const exitPage = sessionStorage.getItem(EXIT_PAGE);
      const current = getCurrentPage();
      if (!current) return;

      if (current === h.TARGET_PAGE && exitPage !== h.TARGET_PAGE.toString()) {
        sessionStorage.removeItem(EXIT_FLAG);
        sessionStorage.removeItem(EXIT_PAGE);

        clearInterval(watcher);
        window.__agamottoOnlineWatcherRunning = false;

        setTimeout(() => location.reload(), 200);
      }
    }, 400);
  }

  document.addEventListener("fullscreenchange", () => {
    const fs = !!document.fullscreenElement;
    const current = getCurrentPage();

    if (fs) {
      sessionStorage.removeItem(EXIT_FLAG);
      sessionStorage.removeItem(EXIT_PAGE);
      sessionStorage.removeItem(EXIT_LOCK);
      return;
    }

    if (!fs) {

      if (current === h.TARGET_PAGE) {
        if (!sessionStorage.getItem(EXIT_LOCK)) {
          sessionStorage.setItem(EXIT_LOCK, "1");
          setTimeout(() => location.reload(), 250);
        }
        return;
      }

      sessionStorage.setItem(EXIT_PAGE, current || "");

      if (!sessionStorage.getItem(EXIT_FLAG)) {
        sessionStorage.setItem(EXIT_FLAG, "1");
        setTimeout(() => location.reload(), 300);
      }

      startTargetPageWatcher();
    }
  });

  window.addEventListener("hashchange", startTargetPageWatcher);
  window.addEventListener("DOMContentLoaded", startTargetPageWatcher);
  window.addEventListener("load", startTargetPageWatcher);

})();
