/* ============================================================
   Shared live Momence schedule embed
   Used by BOTH the Schedule page and the homepage booking module,
   so the real Momence schedule is the single source of truth and
   there is no fabricated class data anywhere on the site.

   TO ADJUST: edit MOMENCE_CFG below (host_id + optional filters).
   Get these from Momence → Studio Setup → "Add Momence to your
   website" → Schedule plugin embed code.
   ============================================================ */

const { Button: MsButton } = window.CalmingSpotDesignSystem_cdab4b;
const { useState: useMsState, useEffect: useMsEffect, useRef: useMsRef } = React;

const MOMENCE_CFG = {
  hostId: "6901",             // Calming Spot Momence host_id (from the Schedule plugin embed code)
  teacherIds: "[]",
  locationIds: "[]",
  tagIds: "[]",
  hideTags: "true",
  defaultFilter: "show-all",
  locale: "en",
  fallbackUrl: "schedule.html", // backup link → our on-site schedule page (where the live embed lives)
};
function momenceConfigured() { return MOMENCE_CFG.hostId.trim() !== ""; }

function MomenceScheduleEmbed() {
  // loading → waiting for plugin to paint · ready → painted ·
  // slow → not painted yet (show non-blocking backup, keep trying) · unset → no host_id
  const [status, setStatus] = useMsState(momenceConfigured() ? "loading" : "unset");
  const mountRef = useMsRef(null);

  useMsEffect(() => {
    if (!momenceConfigured()) return;

    // Inject the Momence host-schedule plugin once per page.
    if (!document.getElementById("momence-host-schedule-js")) {
      const s = document.createElement("script");
      s.id = "momence-host-schedule-js";
      s.async = true;
      s.type = "module";
      s.setAttribute("host_id", MOMENCE_CFG.hostId);
      s.setAttribute("teacher_ids", MOMENCE_CFG.teacherIds);
      s.setAttribute("location_ids", MOMENCE_CFG.locationIds);
      s.setAttribute("tag_ids", MOMENCE_CFG.tagIds);
      s.setAttribute("default_filter", MOMENCE_CFG.defaultFilter);
      s.setAttribute("locale", MOMENCE_CFG.locale);
      s.setAttribute("hide_tags", MOMENCE_CFG.hideTags);
      s.src = "https://momence.com/plugin/host-schedule/host-schedule.js";
      document.body.appendChild(s);
    }

    // The plugin appends its own #momence-plugin-host-schedule to <body>,
    // which lands below the footer. Relocate it into our in-page slot and
    // flip to "ready" once it has painted.
    let ready = false;
    const relocate = () => {
      const host = document.getElementById("momence-plugin-host-schedule");
      if (host && mountRef.current && host.parentNode !== mountRef.current) {
        mountRef.current.appendChild(host);
      }
      if (!ready && host && host.childNodes.length > 0) { ready = true; setStatus("ready"); }
      return ready;
    };
    const obs = new MutationObserver(relocate);
    obs.observe(document.body, { childList: true, subtree: true });
    const slowTimer = setTimeout(() => { if (!relocate()) setStatus("slow"); }, 6000);

    return () => { obs.disconnect(); clearTimeout(slowTimer); };
  }, []);

  return (
    <div className="cs-sched-embed">
      {status === "loading" ? (
        <div className="cs-sched-status" aria-live="polite">
          <span className="cs-sched-spinner" aria-hidden="true" />
          Loading the live schedule…
        </div>
      ) : null}

      {/* Momence renders into #ribbon-schedule — always visible. */}
      <div id="ribbon-schedule" ref={mountRef} className="cs-momence"></div>

      {status === "slow" || status === "unset" ? (
        <div className="cs-sched-fallback">
          <h2 className="cs-sched-fallback__title">Book your next class</h2>
          <p className="cs-sched-fallback__copy">
            {status === "unset"
              ? "Our live schedule is being connected. In the meantime, you can view the full schedule and book your class."
              : "Taking a moment to load? You can view the full schedule and book your class here."}
          </p>
          <MsButton variant="primary" size="lg" href={MOMENCE_CFG.fallbackUrl}>
            View Full Schedule &amp; Book
          </MsButton>
        </div>
      ) : null}
    </div>
  );
}

Object.assign(window, { MomenceScheduleEmbed });
