// Home-page Stumble — pick a random destination from the user-selected pools.
// Pools: topics (~70 nav-link views), books (~37), dictionary (~550).
// Toggle state is persisted to localStorage so the user's mood sticks.
//
// Navigation:
//   - topic view  → location.hash = "#<view>"  (app.js hashchange handler)
//   - book        → window.__openBookAt(id)    (library.js exposed)
//   - dict term   → location.hash = "#dictionary", then trigger popover

(function () {
  const STATE_KEY = "wuys-stumble-pools";

  // Meta-views that aren't standalone content — exclude from topics pool.
  const TOPIC_EXCLUDE = new Set([
    "home", "library", "dictionary", "dictwall", "wordwall", "reader"
  ]);

  function loadState() {
    try {
      const raw = localStorage.getItem(STATE_KEY);
      if (raw) return JSON.parse(raw);
    } catch (e) {}
    return { topics: true, books: true, dict: true };
  }
  function saveState(state) {
    try { localStorage.setItem(STATE_KEY, JSON.stringify(state)); } catch (e) {}
  }

  function listTopicViews() {
    const seen = new Set();
    const out = [];
    document.querySelectorAll(".nav-link[data-view]").forEach((el) => {
      const v = el.dataset.view;
      if (!v || seen.has(v) || TOPIC_EXCLUDE.has(v)) return;
      seen.add(v);
      out.push(v);
    });
    return out;
  }

  function listBookIds() {
    const fn = window.__listBooks;
    if (typeof fn !== "function") return [];
    const all = fn();
    // Only books actually available in the active language.
    return all.filter((b) => b.available).map((b) => b.id);
  }

  function listDictTerms() {
    const lang = (window.i18n && window.i18n.getLang()) || "en";
    const arr = (window.__dictWallData && window.__dictWallData[lang]) || [];
    return arr.map((t) => t[0]); // ids
  }

  function pickRandom(arr) {
    if (!arr || arr.length === 0) return null;
    return arr[Math.floor(Math.random() * arr.length)];
  }

  function gatherEnabledPools(state) {
    const pools = [];
    if (state.topics) {
      const items = listTopicViews();
      if (items.length) pools.push({ name: "topics", items });
    }
    if (state.books) {
      const items = listBookIds();
      if (items.length) pools.push({ name: "books", items });
    }
    if (state.dict) {
      const items = listDictTerms();
      if (items.length) pools.push({ name: "dict", items });
    }
    return pools;
  }

  function navigate(poolName, item) {
    if (poolName === "topics") {
      // Hashchange triggers the app router.
      if (location.hash === "#" + item) {
        // Same view: force a re-show so the user sees navigation feedback.
        location.hash = "#home";
        setTimeout(() => { location.hash = "#" + item; }, 30);
      } else {
        location.hash = "#" + item;
      }
      return;
    }
    if (poolName === "books") {
      if (typeof window.__openBookAt === "function") {
        // Land in the library first so the back-route makes sense, then open.
        if (location.hash !== "#library") location.hash = "#library";
        setTimeout(() => { window.__openBookAt(item); }, 60);
      } else {
        location.hash = "#library";
      }
      return;
    }
    if (poolName === "dict") {
      if (location.hash !== "#dictionary") {
        location.hash = "#dictionary";
      }
      setTimeout(() => {
        const el = document.querySelector('[id="' + item + '"], [data-dict-id="' + item + '"]');
        if (el) {
          el.scrollIntoView({ behavior: "smooth", block: "center" });
          el.classList.add("stumble-flash");
          setTimeout(() => el.classList.remove("stumble-flash"), 1600);
        }
      }, 120);
      return;
    }
  }

  function updateButtonEnabled(state, btn) {
    if (!btn) return;
    const any = state.topics || state.books || state.dict;
    btn.disabled = !any;
  }

  function applyState(state, root) {
    root.querySelectorAll(".stumble-pool").forEach((el) => {
      const k = el.dataset.pool;
      el.classList.toggle("active", !!state[k]);
      el.setAttribute("aria-pressed", state[k] ? "true" : "false");
    });
  }

  function init() {
    const root = document.getElementById("landing-stumble");
    if (!root) return;
    const btn = document.getElementById("stumble-btn");
    let state = loadState();
    applyState(state, root);
    updateButtonEnabled(state, btn);

    root.querySelectorAll(".stumble-pool").forEach((el) => {
      el.addEventListener("click", () => {
        const k = el.dataset.pool;
        state[k] = !state[k];
        // Always keep at least one pool enabled (re-enable the just-toggled one).
        if (!state.topics && !state.books && !state.dict) {
          state[k] = true;
        }
        saveState(state);
        applyState(state, root);
        updateButtonEnabled(state, btn);
      });
    });

    if (btn) {
      btn.addEventListener("click", () => {
        const pools = gatherEnabledPools(state);
        if (pools.length === 0) return;
        const pool = pickRandom(pools);
        const item = pickRandom(pool.items);
        if (item == null) return;
        btn.classList.remove("spinning");
        void btn.offsetWidth;
        btn.classList.add("spinning");
        setTimeout(() => navigate(pool.name, item), 380);
      });
    }
  }

  if (document.readyState === "loading") {
    document.addEventListener("DOMContentLoaded", init);
  } else {
    init();
  }
})();
