// ================= AGAMOTTO SCRIPT for Page 1=================

// ================= Common Helpers =================
const AgamottoHelpers = (function() {
  const TARGET_PAGE = 1;
  const VIEW_CHANGED_FLAG = "agamottoViewChanged";

  let lastFullscreenState = !!document.fullscreenElement;
  let firstLoadDone = false;
  let lastPageKey = location.pathname + location.hash;
  let softReloadDone = new Set();
  let cachedAgamottoEl = null;

  function updateCachedAgamotto() {
    try {
      const el = document.querySelector(".h5p-agamotto");
      if (el !== cachedAgamottoEl) cachedAgamottoEl = el;
      return cachedAgamottoEl;
    } catch (e) { console.error(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) { console.error(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) { console.error(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(n => n.style.overflow="auto"));
    } catch (e) { console.error(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) { console.error(e); return false; }
  }

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

  // expose helpers and shared vars
  return {
    TARGET_PAGE,
    VIEW_CHANGED_FLAG,
    lastFullscreenState,
    firstLoadDone,
    lastPageKey,
    softReloadDone,
    agamottoElement,
    getPageKey,
    getCurrentPageNumber,
    agamottoVisible,
    restoreScrollbars,
    softReloadAgamotto,
    reloadPage
  };
})();

// ================= Local Script =================
(function() {
  const helpers = AgamottoHelpers;
  const reloadPagesKey = "agamottoReloadedPages";

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

    if (!helpers.agamottoVisible()) return;

    if (type === "post-viewchange") {
      helpers.restoreScrollbars();
      const reloadDonePages = new Set(JSON.parse(sessionStorage.getItem(reloadPagesKey) || "[]"));
      reloadDonePages.delete(pageKey);
      sessionStorage.setItem(reloadPagesKey, JSON.stringify([...reloadDonePages]));
      sessionStorage.removeItem(helpers.VIEW_CHANGED_FLAG);
      helpers.reloadPage(400);
      return;
    }

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

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

    // --- Detect view change
    if (helpers.firstLoadDone && fs !== helpers.lastFullscreenState) {
      sessionStorage.setItem(helpers.VIEW_CHANGED_FLAG, "1");
    }

    // --- Reload on TARGET_PAGE if view changed
    if (!fs && page === helpers.TARGET_PAGE && sessionStorage.getItem(helpers.VIEW_CHANGED_FLAG)) {
      performReload("post-viewchange");
      return;
    }

    // --- Soft reload on entering fullscreen
    if (fs && !helpers.softReloadDone.has(pageKey)) {
      performReload("soft-fullscreen");
      return;
    }

    helpers.lastFullscreenState = fs;
    helpers.lastPageKey = pageKey;
    helpers.firstLoadDone = true;
  }

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

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

// ================= ONLINE .gr Script =================
(function() {
  if (!window.location.hostname.includes(".gr")) return;
  const helpers = AgamottoHelpers;

  let lastFullscreenState = !!document.fullscreenElement;
  let firstLoadDone = false;

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

    // --- Detect view change
    if (firstLoadDone && fs !== lastFullscreenState) {
      sessionStorage.setItem(helpers.VIEW_CHANGED_FLAG, "1");
    }

    // --- Reload on TARGET_PAGE if view changed
    if (!fs && page === helpers.TARGET_PAGE && sessionStorage.getItem(helpers.VIEW_CHANGED_FLAG)) {
      sessionStorage.removeItem(helpers.VIEW_CHANGED_FLAG);
      helpers.reloadPage();
      return;
    }

    lastFullscreenState = fs;
    firstLoadDone = true;
  }

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


//opening links in new tab
document.addEventListener('click', function(event) {
const anchor = event.target.closest('a');
if (!anchor) return;

  const href = anchor.getAttribute('href');
  if (!href || (!href.startsWith('http://') && !href.startsWith('https://'))) return;

     event.preventDefault();
     window.open(href, '_blank', 'noopener,noreferrer');
 });