// booking.jsx — embedded third-party booking widget (AutoFlow fleet widget)
const { useEffect: useBookingEffect, useRef: useBookingRef, useState: useBookingState } = React;

const BOOKING_CONFIG = {
  src: "https://getautoflow.io/fleet-widget.js",
  widgetId: "bZltUpDISXSZiQHLiCUsohO7ezQ2",
  theme: "dark",
  color: "#C9A24B",
};

// The vendor script exposes window.FleetWidget.renderWidget(containerId, theme, widgetId, accentColor).
// It does NOT auto-mount, and it bundles its own React — so we load it once, then call render ourselves.
let bookingLoader = null;
function loadBookingScript() {
  if (window.FleetWidget && window.FleetWidget.renderWidget) return Promise.resolve();
  if (bookingLoader) return bookingLoader;
  bookingLoader = new Promise((resolve, reject) => {
    const s = document.createElement("script");
    s.src = BOOKING_CONFIG.src;
    s.async = true;
    s.onload = () => (window.FleetWidget && window.FleetWidget.renderWidget) ? resolve() : reject(new Error("no api"));
    s.onerror = () => reject(new Error("load failed"));
    document.head.appendChild(s);
  });
  bookingLoader.catch(() => { bookingLoader = null; });
  return bookingLoader;
}

function BookingWidget({ id = "booking", eyebrow = "Live Availability", title = "Book Your Vehicle", intro, onFallback }) {
  const hostRef = useBookingRef(null);
  const [state, setState] = useBookingState("loading");

  useBookingEffect(() => {
    const host = hostRef.current;
    if (!host) return;
    let dead = false;
    // The vendor bundle hard-depends on this exact id; only one view mounts at a time so it can't collide.
    const mountId = "fleet-widget-container";
    const mount = document.createElement("div");
    mount.id = mountId;
    host.appendChild(mount);

    loadBookingScript().then(() => {
      if (dead) return;
      window.FleetWidget.renderWidget(mountId, BOOKING_CONFIG.theme, BOOKING_CONFIG.widgetId, BOOKING_CONFIG.color);
      setState("ready");
      setTimeout(() => { if (!dead) setState(mount.childElementCount ? "ready" : "empty"); }, 5000);
    }).catch(() => { if (!dead) setState("error"); });

    return () => { dead = true; host.innerHTML = ""; };
  }, [id]);

  return (
    <section className="section booking-section" id={id}>
      <div className="container">
        <Reveal>
          <div className="section-head">
            <Eyebrow>{eyebrow}</Eyebrow>
            <h2 className="section-title">{title}</h2>
            {intro ? <p className="section-intro">{intro}</p> : null}
          </div>
        </Reveal>
        <Reveal delay={80}>
          <div className="booking-shell" data-state={state}>
            <div className="booking-host" ref={hostRef} />
            {state === "loading" ? <p className="booking-note">Loading live availability…</p> : null}
            {state === "error" || state === "empty" ? (
              <div className="booking-fallback">
                <p className="booking-note">Live booking is unavailable right now.</p>
                {onFallback ? <GoldButton size="md" type="outline" onClick={onFallback}>Reserve by Inquiry</GoldButton> : null}
              </div>
            ) : null}
          </div>
        </Reveal>
      </div>
    </section>
  );
}

Object.assign(window, { BookingWidget, BOOKING_CONFIG });
