const CONFIG = window.PostHogReader || { root: "./", assetVersion: "" };
const ROOT = CONFIG.root || "./";
const VERSION = CONFIG.assetVersion || "";
const STORAGE = {
  saved: "posthog-handbook:saved",
  recent: "posthog-handbook:recent",
  lastSeen: "posthog-handbook:last-seen-edition",
};

function readJSON(key, fallback) {
  try {
    return JSON.parse(localStorage.getItem(key)) || fallback;
  } catch {
    return fallback;
  }
}

function writeJSON(key, value) {
  try {
    localStorage.setItem(key, JSON.stringify(value));
  } catch {}
}

function escapeHTML(value) {
  return String(value)
    .replaceAll("&", "&amp;")
    .replaceAll("<", "&lt;")
    .replaceAll(">", "&gt;")
    .replaceAll('"', "&quot;");
}

function pageUrl() {
  return location.href.split("#")[0];
}

function trimItems(items, limit) {
  return items
    .filter((item) => item && item.url && item.title)
    .filter((item, index, all) => all.findIndex((candidate) => candidate.url === item.url) === index)
    .slice(0, limit);
}

function currentPageMeta() {
  const node = document.querySelector("[data-reader-page]");
  if (!node) return null;
  return {
    title: node.dataset.pageTitle || document.title,
    section: node.dataset.pageSection || "Handbook",
    url: pageUrl(),
    readAt: new Date().toISOString(),
  };
}

function saveRecent(meta) {
  if (!meta) return;
  const recent = readJSON(STORAGE.recent, []);
  writeJSON(STORAGE.recent, trimItems([meta, ...recent], 8));
}

function savedPages() {
  return readJSON(STORAGE.saved, []);
}

function isSaved(url) {
  return savedPages().some((item) => item.url === url);
}

function updateBookmarkButton(button, saved) {
  button.textContent = saved ? "Saved" : "Save page";
  button.setAttribute("aria-pressed", saved ? "true" : "false");
}

function setupBookmark(meta) {
  const button = document.querySelector("[data-bookmark-button]");
  if (!button || !meta) return;
  updateBookmarkButton(button, isSaved(meta.url));
  button.addEventListener("click", () => {
    const saved = savedPages();
    if (saved.some((item) => item.url === meta.url)) {
      writeJSON(STORAGE.saved, saved.filter((item) => item.url !== meta.url));
      updateBookmarkButton(button, false);
    } else {
      writeJSON(STORAGE.saved, trimItems([{ ...meta, savedAt: new Date().toISOString() }, ...saved], 24));
      updateBookmarkButton(button, true);
    }
    renderDashboard();
  });
}

function renderList(target, items, emptyText) {
  if (!target) return;
  if (!items.length) {
    target.innerHTML = `<li class="empty-state">${escapeHTML(emptyText)}</li>`;
    return;
  }
  target.innerHTML = items.map((item) => `<li>
    <a href="${escapeHTML(item.url)}">${escapeHTML(item.title)}</a>
    <span>${escapeHTML(item.section || "Handbook")}</span>
  </li>`).join("");
}

async function offlineCount() {
  if (!("caches" in window)) return null;
  const names = await caches.keys();
  const cacheName = names.find((name) => name.startsWith("posthog-handbook-"));
  if (!cacheName) return null;
  const cache = await caches.open(cacheName);
  return (await cache.keys()).length;
}

async function loadManifest() {
  const response = await fetch(`${ROOT}manifest.json?v=${encodeURIComponent(VERSION)}`);
  return response.json();
}

function setText(selector, text) {
  const node = document.querySelector(selector);
  if (node) node.textContent = text;
}

async function renderDashboard() {
  const dashboard = document.querySelector("[data-reader-dashboard]");
  if (!dashboard) return;
  const recent = readJSON(STORAGE.recent, []);
  const saved = savedPages();
  setText("[data-saved-count]", String(saved.length));
  setText("[data-recent-count]", String(recent.length));
  renderList(document.querySelector("[data-recent-list]"), recent.slice(0, 4), "Open a page and it will appear here.");
  renderList(document.querySelector("[data-saved-list]"), saved.slice(0, 4), "Save useful pages as you read.");
  try {
    const manifest = await loadManifest();
    const previous = localStorage.getItem(STORAGE.lastSeen);
    setText("[data-reader-edition]", manifest.generatedAt || "Current");
    if (previous && previous !== manifest.generatedAt) {
      setText("[data-edition-note]", `New since your last visit: ${manifest.generatedAt}`);
    } else {
      setText("[data-edition-note]", "Current generated edition");
    }
    localStorage.setItem(STORAGE.lastSeen, manifest.generatedAt || "");
  } catch {
    setText("[data-edition-note]", "Edition metadata unavailable offline");
  }
  try {
    const count = await offlineCount();
    setText("[data-offline-status]", count ? "Ready" : "Open once online");
    setText("[data-offline-note]", count ? `${count.toLocaleString()} cached files` : "Cache builds after first visit");
  } catch {
    setText("[data-offline-status]", "Browser managed");
  }
}

const meta = currentPageMeta();
saveRecent(meta);
setupBookmark(meta);
renderDashboard();
