/* ============================================================
   HALO SMS — Guided demo tour (spotlight overlay, role-aware)
   window.Tour — mounted once; driven by a `run` prop.
   Targets stable chrome selectors; skips steps not in the DOM.
   ============================================================ */
(function () {
  const { useState, useEffect, h } = window.HReact;
  const D = window.HALO;

  function buildSteps(role) {
    const isFamily = role === "parent" || role === "student";
    const navSel = isFamily ? ".tabbar" : ".sidebar";
    const contentSel = isFamily ? ".familywrap" : ".page";
    const steps = [
      { center: true, icon: "graduation", title: "Welcome to Halo", body: "A 60-second tour of how this prototype works. You can skip anytime — nothing here is destructive." },
      { sel: ".demobar .ctrls", icon: "swap", title: "The prototype toolbar", body: "This dark strip isn't part of the product — it's for the demo. Switch role, flip light/dark, and change the school's brand here. The product chrome sits below it.", place: "bottom" },
      { sel: navSel, icon: "dashboard", title: isFamily ? "Bottom tabs" : "Navigation", body: isFamily ? "Parents and students get a focused, mobile-first app with tabs along the bottom." : "Staff get a role-aware sidebar — it only shows what this role can actually do.", place: isFamily ? "top" : "right" },
    ];
    if (!isFamily && document.querySelector(".ctxswitch")) steps.push({ sel: ".ctxswitch", icon: "swap", title: "One login, many hats", body: "This is a real feature, not a demo control. Mrs. Adebayo is both a parent and a class teacher — she switches context here without logging out.", place: "bottom" });
    if (isFamily && document.querySelector(".familywrap .csw, .familywrap")) {}
    steps.push({ sel: contentSel, icon: "filetext", title: isFamily ? "Everything in reach" : "The workspace", body: isFamily ? "Fees, results and events — each child's information one tap away, with results fee-gated until balances are settled." : "Lists, forms, the score-entry grid and the signature report sheet all live here, with real empty, loading and error states.", place: "center-ish" });
    steps.push({ center: true, icon: "check", title: "That's the tour", body: "Explore freely — switch roles to see the bursar's finance desk, a teacher's score grid, or the parent app. Re-run this tour anytime from the toolbar." });
    return steps.filter((s) => s.center || document.querySelector(s.sel));
  }

  function Tour({ run, role, onClose }) {
    const [i, setI] = useState(0);
    const [steps, setSteps] = useState([]);
    const [rect, setRect] = useState(null);
    const [, tick] = useState(0);

    useEffect(() => { if (run) { setSteps(buildSteps(role)); setI(0); } }, [run, role]);

    const step = steps[i];
    useEffect(() => {
      if (!run || !step) return;
      function measure() {
        if (step.center || !step.sel) { setRect(null); return; }
        const el = document.querySelector(step.sel);
        if (!el) { setRect(null); return; }
        const r = el.getBoundingClientRect();
        setRect({ top: r.top, left: r.left, width: r.width, height: r.height });
      }
      measure();
      const t = setTimeout(measure, 60);
      window.addEventListener("resize", measure);
      window.addEventListener("scroll", measure, true);
      return () => { clearTimeout(t); window.removeEventListener("resize", measure); window.removeEventListener("scroll", measure, true); };
    }, [run, i, steps]);

    useEffect(() => {
      if (!run) return;
      const onKey = (e) => { if (e.key === "Escape") onClose(); else if (e.key === "ArrowRight") setI((x) => Math.min(steps.length - 1, x + 1)); else if (e.key === "ArrowLeft") setI((x) => Math.max(0, x - 1)); };
      document.addEventListener("keydown", onKey); return () => document.removeEventListener("keydown", onKey);
    }, [run, steps.length]);

    if (!run || !step) return null;
    const pad = 8;
    const spot = rect ? { top: rect.top - pad, left: rect.left - pad, width: rect.width + pad * 2, height: rect.height + pad * 2 } : null;

    // tooltip position
    const TW = 340, vh = window.innerHeight, vw = window.innerWidth;
    let tip;
    if (!spot) tip = { top: vh / 2 - 120, left: vw / 2 - TW / 2 };
    else {
      const below = spot.top + spot.height + 14;
      const above = spot.top - 14;
      if (step.place === "right" && spot.left + spot.width + TW + 24 < vw) tip = { top: Math.max(16, spot.top), left: spot.left + spot.width + 16 };
      else if (step.place === "top" || (below + 200 > vh && above - 200 > 0)) tip = { top: Math.max(16, spot.top - 196), left: clamp(spot.left, vw, TW) };
      else tip = { top: Math.min(vh - 210, below), left: clamp(spot.left, vw, TW) };
    }

    return h("div", { style: { position: "fixed", inset: 0, zIndex: 300 } },
      // click-catcher (advances)
      h("div", { onClick: () => setI((x) => x < steps.length - 1 ? x + 1 : x), style: { position: "absolute", inset: 0, cursor: "pointer" } }),
      // spotlight
      spot
        ? h("div", { style: { position: "absolute", top: spot.top, left: spot.left, width: spot.width, height: spot.height, borderRadius: 12, boxShadow: "0 0 0 9999px rgba(12,14,18,.62)", border: "2px solid var(--brand)", pointerEvents: "none", transition: "all .25s var(--ease)" } })
        : h("div", { style: { position: "absolute", inset: 0, background: "rgba(12,14,18,.62)", pointerEvents: "none" } }),
      // tooltip card
      h("div", { style: { position: "absolute", top: tip.top, left: tip.left, width: TW, background: "var(--surface)", border: "1px solid var(--line)", borderRadius: 16, boxShadow: "var(--shadow-lg)", padding: 20, animation: "pop .2s var(--ease)" } },
        h("div", { className: "row", style: { gap: 11, marginBottom: 10 } },
          h("div", { style: { width: 36, height: 36, borderRadius: 10, flex: "none", background: "var(--brand-soft)", color: "var(--brand-strong)", display: "grid", placeItems: "center" } }, h(Icon, { name: step.icon })),
          h("div", { style: { fontFamily: "var(--fs-display)", fontWeight: 700, fontSize: 16.5, letterSpacing: "-0.01em" } }, step.title)),
        h("p", { style: { fontSize: 13.5, color: "var(--ink-600)", lineHeight: 1.55, margin: 0 } }, step.body),
        h("div", { className: "row", style: { justifyContent: "space-between", marginTop: 18 } },
          h("div", { className: "row", style: { gap: 5 } }, steps.map((_, j) => h("span", { key: j, style: { width: j === i ? 18 : 6, height: 6, borderRadius: 99, background: j === i ? "var(--brand)" : "var(--line)", transition: ".2s" } }))),
          h("div", { className: "row", style: { gap: 8 } },
            i > 0 && h("button", { className: "btn btn-quiet btn-sm", onClick: () => setI(i - 1) }, "Back"),
            i < steps.length - 1
              ? h("button", { className: "btn btn-primary btn-sm", onClick: () => setI(i + 1) }, "Next")
              : h("button", { className: "btn btn-primary btn-sm", onClick: onClose }, "Done")))),
      // skip
      h("button", { className: "btn btn-sm", onClick: onClose, style: { position: "absolute", top: 54, right: 18, background: "rgba(255,255,255,.14)", color: "#fff", border: "1px solid rgba(255,255,255,.25)" } }, "Skip tour"));
  }
  function clamp(left, vw, TW) { return Math.max(16, Math.min(left, vw - TW - 16)); }

  window.Tour = Tour;
})();
