// Calendly is loaded only after a visitor asks to book. No Lens runtime required.
var cwCalendlyPromise;
function loadBookingCalendar() {
  if (window.Calendly) return Promise.resolve(window.Calendly);
  if (cwCalendlyPromise) return cwCalendlyPromise;
  cwCalendlyPromise = new Promise((resolve, reject) => {
    const script = document.createElement("script");
    script.src = "https://assets.calendly.com/assets/external/widget.js";
    script.async = true;
    const fail = (message) => { clearTimeout(timer); script.remove(); cwCalendlyPromise = undefined; reject(new Error(message)); };
    const timer = setTimeout(() => fail("Calendar loading timed out"), 12000);
    script.onload = () => {
      clearTimeout(timer);
      if (window.Calendly) resolve(window.Calendly);
      else fail("Calendar unavailable");
    };
    script.onerror = () => fail("Calendar unavailable");
    document.head.appendChild(script);
  });
  return cwCalendlyPromise;
}

function BookingSection() {
  const ref = useReveal();
  useEffect(() => {
    let cancelled = false, frame;
    const goToBooking = () => {
      (document.fonts ? document.fonts.ready : Promise.resolve()).then(() => {
        if (cancelled || window.location.hash !== "#cta") return;
        frame = requestAnimationFrame(() => document.getElementById("cta")?.scrollIntoView({ behavior: "instant", block: "start" }));
      });
    };
    // The section is rendered after the browser's initial fragment lookup.
    if (document.readyState === "complete") goToBooking();
    else window.addEventListener("load", goToBooking, { once: true });
    return () => { cancelled = true; cancelAnimationFrame(frame); window.removeEventListener("load", goToBooking); };
  }, []);
  return (
    <section id="cta" className="section cw-booking-section">
      <div className="wrap">
        <div ref={ref} className="reveal cw-booking-card">
          <div>
            <div className="eyebrow"><span className="dot" />A clear next step</div>
            <h2 className="h-section">See what to improve. <span className="gradient-text">Know where to start.</span></h2>
            <p className="p-lead">{CW_BOOKING.description}</p>
            <a href={CW_BOOKING.url} data-cw-booking className="btn btn-primary">{CW_BOOKING.label} <i className="ri-arrow-right-line" aria-hidden="true" /></a>
            <p className="cw-booking-note">30 minutes · Live with Edu · No commitment</p>
          </div>
          <div className="cw-booking-agenda">
            <h3>What we’ll cover</h3>
            <ol>
              <li><strong>Your goals and website</strong><span>Walk through the page or flow you want to improve.</span></li>
              <li><strong>2–3 conversion priorities</strong><span>Identify friction and practical opportunities together.</span></li>
              <li><strong>The right next step</strong><span>Decide what to tackle first and whether a deeper audit would help.</span></li>
            </ol>
            <p>The full Shopify Conversion Audit is a separate service starting at $1,000, with a deeper review and prioritized roadmap.</p>
          </div>
        </div>
      </div>
    </section>
  );
}

function BookingDialog() {
  const dialogRef = useRef(null);
  const calendarRef = useRef(null);
  const openerRef = useRef(null);
  const scrollRef = useRef(null);
  const completedRef = useRef(false);
  const [open, setOpen] = useState(false);
  const [status, setStatus] = useState("loading");

  // These events contain no invitee details or unlisted case-study identifiers.
  const measure = (event) => {
    const consent = window.tauristConsent && window.tauristConsent.state();
    if (!consent || consent.analytics_storage !== "granted") return;
    window.dataLayer = window.dataLayer || [];
    window.dataLayer.push({ event, site_surface: "conversion" });
  };
  const close = () => {
    if (dialogRef.current.open) dialogRef.current.close();
  };
  const restore = () => {
    setOpen(false);
    if (scrollRef.current) {
      document.body.style.overflow = scrollRef.current.overflow;
      window.scrollTo({ left: scrollRef.current.x, top: scrollRef.current.y, behavior: "instant" });
      scrollRef.current = null;
    }
    if (openerRef.current && openerRef.current.isConnected) openerRef.current.focus({ preventScroll: true });
  };

  useEffect(() => {
    let frame;
    const onClick = (e) => {
      const anchor = e.target.closest && e.target.closest("a[data-cw-booking]");
      if (!anchor || e.defaultPrevented || e.button !== 0 || e.metaKey || e.ctrlKey || e.shiftKey || e.altKey) return;
      if (!dialogRef.current || typeof dialogRef.current.showModal !== "function") return;
      e.preventDefault();
      openerRef.current = anchor.closest(".nav-mobile-menu") ? document.querySelector(".nav-burger")
        : anchor.closest(".csx-mobcta-panel") ? anchor.closest(".csx-mobcta").querySelector(".csx-mobcta-bar") : anchor;
      // Let React close the mobile navigation and release its scroll lock first.
      frame = requestAnimationFrame(() => {
        if (dialogRef.current.open) return;
        scrollRef.current = { x: window.scrollX, y: window.scrollY, overflow: document.body.style.overflow };
        dialogRef.current.showModal();
        document.body.style.overflow = "hidden";
        setOpen(true);
        measure("cw_booking_opened");
      });
    };
    document.addEventListener("click", onClick);
    return () => { document.removeEventListener("click", onClick); cancelAnimationFrame(frame); };
  }, []);

  useEffect(() => {
    const onMessage = (e) => {
      const iframe = calendarRef.current && calendarRef.current.querySelector("iframe");
      if (e.origin !== "https://calendly.com" || !iframe || e.source !== iframe.contentWindow) return;
      const event = e.data && e.data.event;
      if (["calendly.profile_page_viewed", "calendly.event_type_viewed", "calendly.date_and_time_selected", "calendly.event_scheduled"].includes(event)) setStatus("ready");
      if (event === "calendly.event_scheduled" && !completedRef.current) {
        completedRef.current = true;
        measure("cw_booking_completed");
      }
    };
    window.addEventListener("message", onMessage);
    return () => window.removeEventListener("message", onMessage);
  }, []);

  useEffect(() => {
    if (!open) return;
    let cancelled = false;
    const timer = setTimeout(() => { if (!cancelled) setStatus((current) => current === "loading" ? "slow" : current); }, 15000);
    if (calendarRef.current.querySelector("iframe")) return () => clearTimeout(timer);
    setStatus("loading");
    loadBookingCalendar().then((Calendly) => {
      if (cancelled) return;
      Calendly.initInlineWidget({ url: CW_BOOKING.url + "?primary_color=f22248", parentElement: calendarRef.current });
    }).catch(() => { if (!cancelled) setStatus("error"); });
    return () => { cancelled = true; clearTimeout(timer); };
  }, [open]);

  return (
    <dialog ref={dialogRef} className="cw-booking-dialog" aria-labelledby="cw-booking-title" onClose={restore} onClick={(e) => { if (e.target === dialogRef.current) close(); }}>
      <div className="cw-booking-dialog-inner">
        <header className="cw-booking-dialog-head">
          <div><p>Conversion Works · 30 minutes with Edu</p><h2 id="cw-booking-title">Book a free walkthrough</h2></div>
          <button type="button" className="cw-booking-close" onClick={close} aria-label="Close booking" autoFocus>×</button>
        </header>
        <div className="cw-booking-dialog-help">
          <span role="status">{status === "error" ? "The calendar couldn’t load. You can book directly in Calendly." : status === "slow" ? "Taking longer than expected? You can also book directly." : status === "loading" ? "Loading available times…" : "Choose a time that works for you."}</span>
          <a href={CW_BOOKING.url} target="_blank" rel="noopener noreferrer">Open in Calendly <i className="ri-external-link-line" aria-hidden="true" /></a>
        </div>
        <div ref={calendarRef} className="cw-booking-calendar" aria-label="Calendly scheduling" />
      </div>
    </dialog>
  );
}
