// components/BookingModal.jsx
//
// Shared "Book a discovery call" modal that lazy-loads /booking-widget.html.
//
// Used by:
//   - virtual-assistants.html, services.html, who-we-serve.html (hub pages
//     that didn't have an inline booking widget — the CTA opens this modal
//     instead of bouncing the user to index.html#cta).
//   - playbook/phase4-results.jsx (imports the BookingModal React component
//     directly via window.BookingModal so it can manage its own open state).
//
// Two ways to trigger from a vanilla HTML page:
//   1. Add `data-booking-modal-trigger` to any <button> or <a>. Auto-bound on
//      page load; clicks (and Enter / Space on <a>) open the modal and call
//      preventDefault so href="#" or href="index.html#cta" fallbacks don't fire.
//      Optional: `data-booking-source="hub_cta"` is forwarded to analytics.
//   2. Call window.bluemoso.bookingModal.open(source) / .close() directly.
//
// Why an auto-mounting singleton + data-attribute triggers (not just <BookingModal>)?
//   The three hub pages don't run a React app of their own — they just load a
//   few <script type="text/babel"> components for the nav/footer. A singleton
//   mounted to document.body lets us replace plain <a href="…"> CTAs with
//   <button data-booking-modal-trigger> and have it Just Work, without each
//   page needing to wire up its own React tree.

// ---------------------------------------------------------------------------
// React component (also exported as window.BookingModal for phase4-results.jsx)
// ---------------------------------------------------------------------------

function BookingModal({ open, onClose }) {
  // Lock body scroll + close on Esc while open.
  React.useEffect(() => {
    if (!open) return;
    const prevOverflow = document.body.style.overflow;
    document.body.style.overflow = 'hidden';
    const onKey = (e) => { if (e.key === 'Escape') onClose(); };
    window.addEventListener('keydown', onKey);
    return () => {
      document.body.style.overflow = prevOverflow;
      window.removeEventListener('keydown', onKey);
    };
  }, [open, onClose]);

  if (!open) return null;

  return (
    <div
      onClick={(e) => { if (e.target === e.currentTarget) onClose(); }}
      role="dialog"
      aria-modal="true"
      aria-label="Book a call"
      style={{
        position: 'fixed', inset: 0, zIndex: 1000,
        background: 'rgba(11,31,51,0.55)',
        backdropFilter: 'blur(6px)',
        WebkitBackdropFilter: 'blur(6px)',
        display: 'flex', alignItems: 'flex-start', justifyContent: 'center',
        padding: '24px 16px',
        overflowY: 'auto',
        animation: 'bmFadeIn .2s ease',
      }}
    >
      <style>{`
        @keyframes bmFadeIn { from { opacity: 0; } to { opacity: 1; } }
        @keyframes bmSlideUp { from { opacity: 0; transform: translateY(12px); } to { opacity: 1; transform: translateY(0); } }
      `}</style>
      <div
        style={{
          position: 'relative',
          width: '100%',
          maxWidth: 1280,
          margin: 'auto 0',
          animation: 'bmSlideUp .25s ease',
        }}
      >
        <button
          onClick={onClose}
          aria-label="Close"
          style={{
            position: 'absolute', top: -4, right: 8, zIndex: 2,
            width: 40, height: 40, borderRadius: 999,
            background: '#fff', border: '1px solid rgba(11,31,51,0.12)',
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            color: '#0B1F33',
            cursor: 'pointer',
            boxShadow: '0 4px 12px rgba(0,0,0,0.08)',
          }}
        >
          <svg width="16" height="16" viewBox="0 0 18 18" fill="none" aria-hidden="true"><path d="M4 4l10 10M14 4L4 14" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round"/></svg>
        </button>
        <BookingWidgetMount />
      </div>
    </div>
  );
}

// Fetches /booking-widget.html and re-creates its <script> tags so they execute.
// The widget is self-contained (own styles, markup, and TidyCal-proxy JS), so
// we just need to inject the markup once and let it boot itself.
function BookingWidgetMount() {
  const ref = React.useRef(null);
  React.useEffect(() => {
    const mount = ref.current;
    if (!mount || mount.dataset.loaded === '1') return;
    mount.dataset.loaded = '1';
    let cancelled = false;
    fetch('booking-widget.html')
      .then((r) => r.text())
      .then((html) => {
        if (cancelled) return;
        const tmp = document.createElement('template');
        tmp.innerHTML = html;
        const scripts = [...tmp.content.querySelectorAll('script')];
        scripts.forEach((s) => s.remove());
        mount.appendChild(tmp.content);
        scripts.forEach((s) => {
          const ns = document.createElement('script');
          if (s.src) ns.src = s.src;
          // Wrap inline scripts in an IIFE so re-mounting (open → close → open)
          // doesn't collide with `const`-declared globals from a previous mount.
          else ns.textContent = '(function(){\n' + s.textContent + '\n})();';
          mount.appendChild(ns);
        });
      })
      .catch((e) => {
        console.error('Failed to load booking widget:', e);
        mount.innerHTML =
          '<div style="text-align:center;padding:48px;color:#5C6275;background:#fff;border-radius:16px;">' +
          'Booking widget failed to load. ' +
          '<a href="https://tidycal.com/coryblumenfeld/intro-meeting-m5ww00z">Book directly.</a>' +
          '</div>';
      });
    return () => { cancelled = true; };
  }, []);
  return <div ref={ref} />;
}

// ---------------------------------------------------------------------------
// Singleton auto-mount
// ---------------------------------------------------------------------------
//
// On page load, drop a hidden host <div> on body, render a stateful
// <BookingModalApp> into it, and wire up:
//   - window.bluemoso.bookingModal.open(source?)
//   - window.bluemoso.bookingModal.close()
//   - delegated click handler for [data-booking-modal-trigger]

function BookingModalApp() {
  const [open, setOpen] = React.useState(false);

  // Expose imperative open/close so vanilla code can drive the modal.
  React.useEffect(() => {
    window.bluemoso = window.bluemoso || {};
    window.bluemoso.bookingModal = {
      open: function (source) {
        setOpen(true);
        try {
          if (window.bluemoso && window.bluemoso.analytics) {
            window.bluemoso.analytics.track('booking_modal_open', {
              source: source || 'unknown',
            });
          }
        } catch (e) { /* analytics is best-effort */ }
      },
      close: function () { setOpen(false); },
      isOpen: function () { return open; },
    };
  }, [open]);

  return <BookingModal open={open} onClose={() => setOpen(false)} />;
}

(function autoMount() {
  if (typeof window === 'undefined' || !document) return;

  function mount() {
    // Idempotent — never double-mount, even if this script is loaded twice.
    if (document.getElementById('bm-booking-modal-host')) return;
    const host = document.createElement('div');
    host.id = 'bm-booking-modal-host';
    document.body.appendChild(host);

    // Use ReactDOM.createRoot when available (React 18+).
    if (window.ReactDOM && window.ReactDOM.createRoot) {
      window.ReactDOM.createRoot(host).render(<BookingModalApp />);
    } else if (window.ReactDOM && window.ReactDOM.render) {
      window.ReactDOM.render(<BookingModalApp />, host);
    } else {
      console.warn('[BookingModal] ReactDOM not available; modal will not mount.');
      return;
    }

    // Delegated click handler — works for buttons added later by other scripts.
    document.addEventListener('click', function (e) {
      const trigger = e.target.closest('[data-booking-modal-trigger]');
      if (!trigger) return;
      e.preventDefault();
      const source = trigger.getAttribute('data-booking-source') || 'cta_button';
      if (window.bluemoso && window.bluemoso.bookingModal) {
        window.bluemoso.bookingModal.open(source);
      }
    });
  }

  if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', mount);
  } else {
    mount();
  }
})();

// Expose React component too, so phase4-results.jsx can keep managing its own
// open state instead of going through the global singleton.
Object.assign(window, { BookingModal });
