// Onboarding Tour — first-visit guided overlay.
// Steps are spotlight + adjacent card. localStorage flag suppresses replay.
// Replay via the "Take the tour" pill in landing-closing.
//
// Each step:
//   { target: CSS selector | null, titleKey, bodyKey, placement?: "auto"|"center" }
// target=null OR placement="center" → centered card, flat dim, no spotlight hole.

(function () {
  const DONE_KEY = "wuys-tour-seen";

  const STEPS = [
    { target: null,                                    titleKey: "tour.s1.title", bodyKey: "tour.s1.body" },
    { target: ".nav-categories",                       titleKey: "tour.s2.title", bodyKey: "tour.s2.body" },
    { target: ".landing-rooms",                        titleKey: "tour.s3.title", bodyKey: "tour.s3.body" },
    { target: "#landing-stumble",                      titleKey: "tour.s4.title", bodyKey: "tour.s4.body" },
    { target: '.nav-cat[data-cat="library"]',          titleKey: "tour.s5.title", bodyKey: "tour.s5.body" },
    { target: '.nav-cat[data-cat="dictionary"]',       titleKey: "tour.s6.title", bodyKey: "tour.s6.body" },
    { target: "#downloadOpen",                         titleKey: "tour.s7.title", bodyKey: "tour.s7.body" },
    { target: "#tourOpen",                             titleKey: "tour.s8.title", bodyKey: "tour.s8.body" },
    { target: ".lang-switcher",                        titleKey: "tour.s9.title", bodyKey: "tour.s9.body" }
  ];

  function L() { return (window.__langData && window.__langData[(window.i18n && window.i18n.getLang()) || "en"]) || {}; }
  function t(key, fallback) { return L()[key] != null ? L()[key] : (fallback != null ? fallback : key); }

  let idx = 0;
  let active = false;

  function $(id) { return document.getElementById(id); }

  function setText(el, val) { if (el) el.textContent = val; }

  function applyI18nToOverlay() {
    setText($("tour-step-total"), String(STEPS.length));
    const skip = $("tour-skip"); if (skip) skip.textContent = t("tour.skip", "Skip");
    const prev = $("tour-prev"); if (prev) prev.textContent = t("tour.prev", "← Back");
    const next = $("tour-next"); if (next) next.textContent = t("tour.next", "Next →");
    const done = $("tour-done"); if (done) done.textContent = t("tour.done", "Done");
  }

  function isFinalStep() { return idx === STEPS.length - 1; }

  function clamp(v, lo, hi) { return Math.max(lo, Math.min(hi, v)); }

  function placeCardForRect(card, rect) {
    const vw = window.innerWidth;
    const vh = window.innerHeight;
    const cw = card.offsetWidth;
    const ch = card.offsetHeight;
    const gap = 16;
    // Prefer below the target, then above, then to the side, otherwise center.
    let top, left;
    const spaceBelow = vh - rect.bottom;
    const spaceAbove = rect.top;
    const spaceRight = vw - rect.right;
    const spaceLeft = rect.left;
    if (spaceBelow >= ch + gap + 20) {
      top = rect.bottom + gap;
      left = clamp(rect.left + rect.width / 2 - cw / 2, 16, vw - cw - 16);
    } else if (spaceAbove >= ch + gap + 20) {
      top = rect.top - ch - gap;
      left = clamp(rect.left + rect.width / 2 - cw / 2, 16, vw - cw - 16);
    } else if (spaceRight >= cw + gap + 20) {
      left = rect.right + gap;
      top = clamp(rect.top + rect.height / 2 - ch / 2, 16, vh - ch - 16);
    } else if (spaceLeft >= cw + gap + 20) {
      left = rect.left - cw - gap;
      top = clamp(rect.top + rect.height / 2 - ch / 2, 16, vh - ch - 16);
    } else {
      top = vh / 2 - ch / 2;
      left = vw / 2 - cw / 2;
    }
    card.style.top = top + "px";
    card.style.left = left + "px";
  }

  function placeCardCenter(card) {
    card.style.top = "50%";
    card.style.left = "50%";
    card.style.transform = "translate(-50%, -50%)";
  }

  function placeSpotlightForRect(spot, rect) {
    const pad = 8;
    spot.classList.remove("tour-spotlight-center");
    spot.style.top = (rect.top - pad) + "px";
    spot.style.left = (rect.left - pad) + "px";
    spot.style.width = (rect.width + pad * 2) + "px";
    spot.style.height = (rect.height + pad * 2) + "px";
  }

  function placeSpotlightCenter(spot) {
    spot.classList.add("tour-spotlight-center");
    spot.style.top = "50%";
    spot.style.left = "50%";
    spot.style.width = "0";
    spot.style.height = "0";
  }

  function scrollIntoViewIfNeeded(el) {
    const rect = el.getBoundingClientRect();
    const vh = window.innerHeight;
    if (rect.top < 0 || rect.bottom > vh) {
      el.scrollIntoView({ behavior: "smooth", block: "center" });
    }
  }

  function showStep() {
    if (!active) return;
    const step = STEPS[idx];
    const overlay = $("tour-overlay");
    const card = $("tour-card");
    const spot = $("tour-spotlight");
    if (!overlay || !card || !spot) return;

    setText($("tour-step-n"), String(idx + 1));
    setText($("tour-title"), t(step.titleKey, ""));
    setText($("tour-body"), t(step.bodyKey, ""));

    const prevBtn = $("tour-prev");
    if (prevBtn) prevBtn.disabled = idx === 0;
    const nextBtn = $("tour-next");
    const doneBtn = $("tour-done");
    if (isFinalStep()) {
      if (nextBtn) nextBtn.hidden = true;
      if (doneBtn) doneBtn.hidden = false;
    } else {
      if (nextBtn) nextBtn.hidden = false;
      if (doneBtn) doneBtn.hidden = true;
    }

    // Resolve target element
    let targetEl = null;
    if (step.target) targetEl = document.querySelector(step.target);

    card.style.transform = "";
    if (!targetEl || step.placement === "center") {
      placeSpotlightCenter(spot);
      // Defer to next frame so width/height are known.
      requestAnimationFrame(() => placeCardCenter(card));
      return;
    }

    scrollIntoViewIfNeeded(targetEl);
    // Wait for the scroll to settle before measuring.
    setTimeout(() => {
      const rect = targetEl.getBoundingClientRect();
      placeSpotlightForRect(spot, rect);
      requestAnimationFrame(() => placeCardForRect(card, rect));
    }, 320);
  }

  function next() {
    if (isFinalStep()) { finish(); return; }
    idx++;
    showStep();
  }
  function prev() {
    if (idx === 0) return;
    idx--;
    showStep();
  }
  function finish() {
    active = false;
    try { localStorage.setItem(DONE_KEY, "1"); } catch (e) {}
    const overlay = $("tour-overlay");
    if (overlay) overlay.hidden = true;
    document.body.style.overflow = "";
    window.removeEventListener("resize", onResize);
  }
  function onResize() {
    if (active) showStep();
  }

  function start(force) {
    if (active) return;
    if (!force) {
      try { if (localStorage.getItem(DONE_KEY) === "1") return; } catch (e) {}
    }
    const onHome = document.querySelector('.view[data-view="home"]')?.classList.contains("active");
    // Auto-start: only on home. Forced replay: navigate to home first if elsewhere.
    if (!force && !onHome) return;
    if (force && !onHome) {
      // Safety cap: if the home view never activates (e.g. a non-router view
      // like the reader owns the screen while the hash is already "#home"),
      // stop retrying instead of looping forever and bricking the menu.
      start._tries = (start._tries || 0) + 1;
      if (start._tries > 10) { start._tries = 0; return; }
      if (location.hash !== "#home") location.hash = "#home";
      // Wait for view switch + layout, then start.
      setTimeout(() => { active = false; start(true); }, 280);
      return;
    }
    start._tries = 0;

    idx = 0;
    active = true;
    applyI18nToOverlay();
    const overlay = $("tour-overlay");
    if (!overlay) return;
    overlay.hidden = false;
    document.body.style.overflow = "hidden";
    window.addEventListener("resize", onResize);
    // Give layout one tick.
    setTimeout(showStep, 50);
  }

  function bindControls() {
    $("tour-skip")?.addEventListener("click", finish);
    $("tour-next")?.addEventListener("click", next);
    $("tour-prev")?.addEventListener("click", prev);
    $("tour-done")?.addEventListener("click", finish);
    $("tour-replay")?.addEventListener("click", () => start(true));
    $("tourOpen")?.addEventListener("click", () => start(true));
    document.addEventListener("keydown", (ev) => {
      if (!active) return;
      if (ev.key === "Escape") finish();
      else if (ev.key === "ArrowRight" || ev.key === "Enter") next();
      else if (ev.key === "ArrowLeft") prev();
    });
    window.addEventListener("langchange", () => {
      if (active) {
        applyI18nToOverlay();
        showStep();
      }
    });
  }

  function init() {
    bindControls();
    // Auto-start on first visit after a short delay so other init (i18n, stumble) settles.
    setTimeout(() => start(false), 900);
  }

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

  // Expose manual start for any future entry points.
  window.__startTour = (force) => start(!!force);
})();
