// Square Appointments booking widget modal (TypeScript).
//
// Embeds Square's own hosted booking page in an iframe. Because the booking is
// *customer-initiated* on Square's site, it lands as a PENDING appointment for
// staff to accept or decline — which the seller-token Bookings API path cannot
// do (it auto-accepts). This is the whole reason we route "Book" here.
//
// The booking URL lives in window.RIO3_SQUARE_BOOKING_URL (set in index.html),
// so pointing at a different Square account / location is a one-line change.
// Empty string → graceful "call us" fallback.
//
// Loaded as a global script — no import/export. Published on window at the end.

const SQUARE_BOOKING_URL: string = (window.RIO3_SQUARE_BOOKING_URL || "").trim();

const BookingWidgetModal = ({ onClose }: { onClose: () => void }) => {
  const [loaded, setLoaded] = React.useState(false);
  const { brand } = window.RIO3_DATA;
  const hasUrl = !!SQUARE_BOOKING_URL;

  React.useEffect(() => {
    const onKey = (e: KeyboardEvent) => { if (e.key === "Escape") onClose(); };
    window.addEventListener("keydown", onKey);
    document.body.style.overflow = "hidden";
    return () => { window.removeEventListener("keydown", onKey); document.body.style.overflow = ""; };
  }, [onClose]);

  return (
    <div className="modal-back" onClick={onClose}>
      <div className="modal booking-widget-modal" onClick={(e) => e.stopPropagation()}>
        <button className="modal-close" onClick={onClose} aria-label="Close">&times;</button>

        {hasUrl ? (
          <div className="booking-embed">
            {!loaded && (
              <div className="booking-embed-loading" aria-live="polite">
                <span className="booking-spinner" aria-hidden="true" />
                <span>Loading booking…</span>
              </div>
            )}
            <iframe
              className="booking-embed-frame"
              src={SQUARE_BOOKING_URL}
              title="Book an appointment with Rio3"
              loading="lazy"
              allow="payment"
              onLoad={() => setLoaded(true)}
            />
            <div className="booking-embed-foot">
              Trouble booking?{" "}
              <a href={SQUARE_BOOKING_URL} target="_blank" rel="noopener noreferrer">Open in a new tab</a>
              {" · or call "}
              <a href={`tel:${brand.phone}`}>{brand.phone}</a>
            </div>
          </div>
        ) : (
          <div className="booking-embed-fallback">
            <Brand size={40} />
            <h3>Book your visit</h3>
            <p>Call us and our team will find a time that works for you.</p>
            <a className="btn btn-primary" href={`tel:${brand.phone}`}>
              Call {brand.phone} <Arrow />
            </a>
          </div>
        )}
      </div>
    </div>
  );
};

Object.assign(window, { BookingWidgetModal });
