/* ------------------------------------------------------------------
   HyperFocusOZ — Booking modal
   ------------------------------------------------------------------
   Custom-front-end booking flow that embeds Microsoft Bookings.

   ┌─────────────────────────────────────────────────────────────────┐
   │  SETUP — replace the URLs in BOOKING_SERVICES below with the    │
   │  three Microsoft Bookings service URLs from your tenant.        │
   │                                                                 │
   │  How to find them:                                              │
   │  1. Go to https://outlook.office.com/bookings                   │
   │  2. Open your Booking page → Services → click a service         │
   │  3. Copy the public booking URL — it looks like:                │
   │     https://outlook.office.com/bookwithme/user/{id}             │
   │       /meetingtype/{meetingId}?anonymous                        │
   │  4. Paste it into the matching service below.                   │
   │                                                                 │
   │  Until URLs are swapped in, the modal shows a helpful           │
   │  "configuration pending" panel instead of the iframe.           │
   └─────────────────────────────────────────────────────────────────*/

const BOOKING_CONFIG = /*EDITMODE-BEGIN*/{
  "discoveryUrl": "https://outlook.office.com/book/HyperFocusBookings1@hyperfocusoz.com/?ismsaljsauthenabled",
  "scopingUrl":   "https://outlook.office.com/book/HyperFocusBookings1@hyperfocusoz.com/?ismsaljsauthenabled",
  "kickoffUrl":   "https://outlook.office.com/book/HyperFocusBookings1@hyperfocusoz.com/?ismsaljsauthenabled"
}/*EDITMODE-END*/;

const BOOKING_SERVICES = [
  {
    id: 'discovery',
    num: '01',
    title: 'Discovery call',
    duration: '30 minutes',
    cost: 'No charge',
    desc: 'A conversation about your goals, constraints, and stack. No slides, no sales pitch — honest answer on fit.',
    bullets: ['Whether we can help', 'What we\'d do first', 'Rough size and shape'],
    urlKey: 'discoveryUrl',
    featured: true,
  },
  {
    id: 'scoping',
    num: '02',
    title: 'Scoping session',
    duration: '60 minutes',
    cost: 'No charge',
    desc: 'Deeper working session once a discovery call says it\'s a fit. We map the flow, identify the wins, sketch a proposal.',
    bullets: ['Process walkthrough', 'AI / automation opportunities', 'Cost & timeline framework'],
    urlKey: 'scopingUrl',
    featured: false,
  },
  {
    id: 'kickoff',
    num: '03',
    title: 'Quick Win kickoff',
    duration: '90 minutes',
    cost: 'Included with engagement',
    desc: 'Kickoff for an approved Quick Win. We align on outcomes, access, and a 2-week delivery plan.',
    bullets: ['Outcomes locked in', 'Stack & access ready', 'Working software in 2 weeks'],
    urlKey: 'kickoffUrl',
    featured: false,
  },
];

const { useEffect, useState, useRef, useCallback } = React;

// All component definitions and mount logic live inside this IIFE so internal
// names (ServiceCard, ModalHeader, etc.) don't collide with components defined
// in other Babel-loaded files (e.g. site-sections.jsx also defines ServiceCard).
(function () {

// ---------------------------------------------------------------- //
// Backdrop + container
// ---------------------------------------------------------------- //
function BookingModal({ initialServiceId, onClose }) {
  const [serviceId, setServiceId] = useState(initialServiceId || null);
  const dialogRef = useRef(null);

  // Lock body scroll
  useEffect(() => {
    const prev = document.body.style.overflow;
    document.body.style.overflow = 'hidden';
    return () => { document.body.style.overflow = prev; };
  }, []);

  // ESC to close
  useEffect(() => {
    const onKey = (e) => { if (e.key === 'Escape') onClose(); };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, [onClose]);

  // Focus dialog on open
  useEffect(() => {
    setTimeout(() => dialogRef.current && dialogRef.current.focus(), 60);
  }, []);

  const service = BOOKING_SERVICES.find(s => s.id === serviceId);

  return (
    <div
      role="dialog"
      aria-modal="true"
      aria-label="Book a call with HyperFocusOZ"
      onClick={(e) => { if (e.target === e.currentTarget) onClose(); }}
      style={{
        position: 'fixed', inset: 0, zIndex: 9999,
        background: 'rgba(20, 15, 10, 0.62)',
        backdropFilter: 'blur(6px) saturate(140%)',
        WebkitBackdropFilter: 'blur(6px) saturate(140%)',
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        padding: 'clamp(12px, 3vw, 32px)',
        animation: 'hf-fadeIn 200ms ease-out',
      }}
    >
      <div
        ref={dialogRef}
        tabIndex={-1}
        style={{
          width: '100%',
          maxWidth: service ? 760 : 820,
          maxHeight: '92vh',
          background: 'var(--bg)',
          color: 'var(--fg)',
          borderRadius: 14,
          boxShadow: '0 30px 80px -20px rgba(20,15,10,0.55), 0 0 0 1px rgba(20,15,10,0.06)',
          overflow: 'hidden',
          display: 'flex', flexDirection: 'column',
          animation: 'hf-popIn 240ms cubic-bezier(0.16, 1, 0.3, 1)',
          outline: 'none',
        }}
      >
        <ModalHeader
          service={service}
          onBack={service ? () => setServiceId(null) : null}
          onClose={onClose}
        />
        <div style={{ overflow: 'auto', flex: 1, minHeight: 0 }}>
          {!service && <ServicePicker onPick={setServiceId} />}
          {service && <ServiceBooking service={service} />}
        </div>
      </div>
      <style>{`
        @keyframes hf-fadeIn { from {opacity:0} to {opacity:1} }
        @keyframes hf-popIn {
          from { opacity: 0; transform: translateY(8px) scale(0.985); }
          to   { opacity: 1; transform: translateY(0)   scale(1); }
        }
        .hf-booking-card {
          transition: transform 200ms cubic-bezier(0.16,1,0.3,1),
                      border-color 200ms ease,
                      background 200ms ease,
                      box-shadow 200ms ease;
        }
        .hf-booking-card:hover {
          transform: translateY(-2px);
          border-color: var(--ember);
          box-shadow: 0 18px 40px -22px rgba(194,97,31,0.45);
        }
        .hf-booking-card:hover .hf-booking-arrow { transform: translateX(3px); }
        .hf-booking-arrow { transition: transform 200ms ease; }
        .hf-booking-close:hover { background: rgba(20,15,10,0.08); }
        [data-theme="dark"] .hf-booking-close:hover { background: rgba(243,238,228,0.10); }
      `}</style>
    </div>
  );
}

// ---------------------------------------------------------------- //
// Header
// ---------------------------------------------------------------- //
function ModalHeader({ service, onBack, onClose }) {
  return (
    <div style={{
      display: 'flex', alignItems: 'center', justifyContent: 'space-between',
      padding: '18px 22px',
      borderBottom: '1px solid var(--line)',
      gap: 12,
    }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 14, minWidth: 0 }}>
        {onBack && (
          <button
            onClick={onBack}
            aria-label="Back to service picker"
            className="hf-booking-close"
            style={{
              width: 32, height: 32, borderRadius: 6, border: '1px solid var(--line)',
              background: 'transparent', color: 'var(--fg)', cursor: 'pointer',
              display: 'flex', alignItems: 'center', justifyContent: 'center',
              fontSize: 16, lineHeight: 1, padding: 0, flex: '0 0 auto',
            }}
          >‹</button>
        )}
        <div style={{ display: 'flex', alignItems: 'baseline', gap: 8, minWidth: 0 }}>
          <span style={{
            fontWeight: 700, fontSize: 18, letterSpacing: '-0.022em',
            whiteSpace: 'nowrap'
          }}>hyperfocusoz</span>
          <span style={{
            display: 'inline-block', width: 7, height: 7, borderRadius: '50%',
            background: 'var(--ember)', transform: 'translateY(-1px)'
          }} />
          <span className="mono" style={{
            fontSize: 11, color: 'var(--muted)', letterSpacing: '0.14em',
            textTransform: 'uppercase', marginLeft: 10,
            whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis',
          }}>
            // {service ? service.title : 'Book a time'}
          </span>
        </div>
      </div>
      <button
        onClick={onClose}
        aria-label="Close"
        className="hf-booking-close"
        style={{
          width: 32, height: 32, borderRadius: 6, border: '1px solid var(--line)',
          background: 'transparent', color: 'var(--fg)', cursor: 'pointer',
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          fontSize: 18, lineHeight: 1, padding: 0, flex: '0 0 auto',
        }}
      >×</button>
    </div>
  );
}

// ---------------------------------------------------------------- //
// Step 1: pick a service
// ---------------------------------------------------------------- //
function ServicePicker({ onPick }) {
  return (
    <div style={{ padding: 'clamp(22px, 4vw, 36px)' }}>
      <div style={{ marginBottom: 22 }}>
        <div className="mono" style={{
          fontSize: 11, letterSpacing: '0.18em', textTransform: 'uppercase',
          color: 'var(--ember)', marginBottom: 10,
        }}>
          // step 1 of 2
        </div>
        <h2 style={{
          fontSize: 'clamp(24px, 3.4vw, 34px)', fontWeight: 700,
          letterSpacing: '-0.025em', lineHeight: 1.08, margin: 0,
          textWrap: 'balance',
        }}>
          What kind of conversation
          {' '}<span style={{ color: 'var(--ember)' }}>are we having?</span>
        </h2>
        <p style={{
          fontSize: 15, lineHeight: 1.55, color: 'var(--muted)',
          margin: '12px 0 0', maxWidth: 600,
        }}>
          Pick a meeting type, then choose a time that works. Calendar invites land in your inbox automatically.
        </p>
      </div>

      <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
        {BOOKING_SERVICES.map(s => (
          <ServiceCard key={s.id} service={s} onPick={() => onPick(s.id)} />
        ))}
      </div>

      <div style={{
        marginTop: 22, paddingTop: 18, borderTop: '1px dashed var(--line)',
        display: 'flex', flexWrap: 'wrap', gap: 12,
        fontSize: 12, color: 'var(--muted)',
      }}>
        <span className="mono" style={{ letterSpacing: '0.06em' }}>
          // Powered by Microsoft Bookings · AEST/AEDT default
        </span>
        <span style={{ marginLeft: 'auto' }}>
          Prefer email? <a href="mailto:hello@hyperfocusoz.com" className="hf-ulink"
            style={{ color: 'var(--fg)', fontWeight: 600 }}>hello@hyperfocusoz.com</a>
        </span>
      </div>
    </div>
  );
}

function ServiceCard({ service, onPick }) {
  const { num, title, duration, cost, desc, bullets, featured } = service;
  return (
    <button
      onClick={onPick}
      className="hf-booking-card"
      style={{
        position: 'relative',
        textAlign: 'left', cursor: 'pointer',
        background: featured ? 'color-mix(in oklab, var(--ember) 5%, var(--bg))' : 'var(--bg)',
        border: `1px solid ${featured ? 'color-mix(in oklab, var(--ember) 35%, var(--line))' : 'var(--line)'}`,
        borderRadius: 10,
        padding: '18px 20px',
        color: 'var(--fg)',
        display: 'grid',
        gridTemplateColumns: 'auto 1fr auto',
        gap: 18,
        alignItems: 'center',
        fontFamily: 'inherit',
      }}
    >
      <div style={{
        fontFamily: 'var(--mono, "JetBrains Mono", ui-monospace, monospace)',
        fontSize: 11, color: 'var(--muted)', letterSpacing: '0.06em',
        flex: '0 0 auto', alignSelf: 'flex-start', paddingTop: 4,
      }}>
        {num}
      </div>
      <div style={{ minWidth: 0 }}>
        <div style={{ display: 'flex', alignItems: 'baseline', gap: 10, flexWrap: 'wrap' }}>
          <span style={{
            fontSize: 18, fontWeight: 700, letterSpacing: '-0.015em',
          }}>{title}</span>
          <span className="mono" style={{
            fontSize: 11, color: 'var(--muted)', letterSpacing: '0.06em',
          }}>
            {duration} · {cost}
          </span>
        </div>
        <p style={{
          fontSize: 14, lineHeight: 1.55, color: 'var(--muted)',
          margin: '6px 0 10px', textWrap: 'pretty',
        }}>{desc}</p>
        <ul style={{
          listStyle: 'none', padding: 0, margin: 0,
          display: 'flex', flexWrap: 'wrap', gap: '6px 14px',
          fontSize: 12, color: 'var(--fg)',
        }}>
          {bullets.map((b) => (
            <li key={b} style={{
              display: 'flex', alignItems: 'center', gap: 6,
            }}>
              <span style={{
                width: 4, height: 4, borderRadius: '50%',
                background: 'var(--ember)', flex: '0 0 auto',
              }} />
              <span>{b}</span>
            </li>
          ))}
        </ul>
      </div>
      <div style={{
        display: 'flex', alignItems: 'center', gap: 6,
        fontSize: 13, fontWeight: 600, color: 'var(--ember)',
        flex: '0 0 auto', alignSelf: 'center',
      }}>
        <span>Choose</span>
        <span className="hf-booking-arrow" style={{ display: 'inline-block' }}>→</span>
      </div>
    </button>
  );
}

// ---------------------------------------------------------------- //
// Step 2: embed the actual Microsoft Bookings page
// ---------------------------------------------------------------- //
function ServiceBooking({ service }) {
  const url = BOOKING_CONFIG[service.urlKey];
  const configured = url && url !== 'PLACEHOLDER' && url.includes('http');

  return (
    <div style={{
      display: 'grid',
      gridTemplateColumns: 'minmax(0, 1fr) 440px',
      minHeight: 600,
    }}
    className="hf-booking-grid"
    >
      <style>{`
        @media (max-width: 860px) {
          .hf-booking-grid { grid-template-columns: 1fr !important; }
          .hf-booking-sidebar { border-right: none !important; border-bottom: 1px solid var(--line) !important; }
        }
      `}</style>
      {/* Left: meeting summary in HF style */}
      <aside
        className="hf-booking-sidebar"
        style={{
          padding: 'clamp(22px, 3vw, 32px)',
          borderRight: '1px solid var(--line)',
          background: 'color-mix(in oklab, var(--ember) 4%, var(--bg))',
          display: 'flex', flexDirection: 'column', gap: 18,
        }}
      >
        <div>
          <div className="mono" style={{
            fontSize: 11, letterSpacing: '0.18em', textTransform: 'uppercase',
            color: 'var(--ember)', marginBottom: 8,
          }}>
            // step 2 of 2 · {service.num}
          </div>
          <h3 style={{
            fontSize: 'clamp(22px, 2.6vw, 28px)', fontWeight: 700,
            letterSpacing: '-0.022em', lineHeight: 1.1, margin: 0,
            textWrap: 'balance',
          }}>{service.title}</h3>
        </div>

        <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
          <SummaryRow k="duration" v={service.duration} />
          <SummaryRow k="cost" v={service.cost} />
          <SummaryRow k="format" v="video call · AEST/AEDT" />
        </div>

        <div style={{ paddingTop: 14, borderTop: '1px dashed var(--line)' }}>
          <div className="mono" style={{
            fontSize: 11, letterSpacing: '0.18em', textTransform: 'uppercase',
            color: 'var(--muted)', marginBottom: 8,
          }}>
            // what we cover
          </div>
          <ul style={{
            listStyle: 'none', padding: 0, margin: 0,
            display: 'flex', flexDirection: 'column', gap: 8,
            fontSize: 14, color: 'var(--fg)',
          }}>
            {service.bullets.map((b) => (
              <li key={b} style={{ display: 'flex', gap: 10, alignItems: 'flex-start' }}>
                <span style={{
                  width: 5, height: 5, borderRadius: '50%',
                  background: 'var(--ember)', marginTop: 8, flex: '0 0 auto',
                }} />
                <span style={{ lineHeight: 1.5 }}>{b}</span>
              </li>
            ))}
          </ul>
        </div>

        <div style={{
          marginTop: 'auto', paddingTop: 18,
          fontSize: 12, color: 'var(--muted)', lineHeight: 1.5,
        }}>
          Trouble with the picker? Email{' '}
          <a href="mailto:hello@hyperfocusoz.com" className="hf-ulink"
            style={{ color: 'var(--fg)', fontWeight: 600 }}>
            hello@hyperfocusoz.com
          </a>{' '}and we'll find a time manually.
        </div>
      </aside>

      {/* Right: the actual booking iframe */}
      <div style={{ position: 'relative', minHeight: 600, background: 'var(--bg)' }}>
        {configured ? (
          <iframe
            src={url}
            title={`Book ${service.title}`}
            style={{
              border: 'none', width: '100%', height: '100%',
              minHeight: 600, display: 'block',
              background: '#fff', /* MS Bookings is light only */
            }}
            allow="microphone; camera"
          />
        ) : (
          <BookingNotConfigured serviceKey={service.urlKey} />
        )}
      </div>
    </div>
  );
}

function SummaryRow({ k, v }) {
  return (
    <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', gap: 12 }}>
      <span className="mono" style={{
        fontSize: 11, color: 'var(--muted)', letterSpacing: '0.16em',
        textTransform: 'uppercase',
      }}>{k}</span>
      <span style={{ fontSize: 14, fontWeight: 600, textAlign: 'right' }}>{v}</span>
    </div>
  );
}

function BookingNotConfigured({ serviceKey }) {
  return (
    <div style={{
      padding: '40px 32px', height: '100%', minHeight: 600,
      display: 'flex', flexDirection: 'column', justifyContent: 'center',
      gap: 16, maxWidth: 520,
    }}>
      <div className="mono" style={{
        fontSize: 11, letterSpacing: '0.18em', textTransform: 'uppercase',
        color: 'var(--ember)',
      }}>// setup pending</div>
      <h3 style={{
        fontSize: 26, fontWeight: 700, letterSpacing: '-0.022em',
        lineHeight: 1.15, margin: 0,
      }}>
        Microsoft Bookings URL not yet wired up.
      </h3>
      <p style={{ fontSize: 15, lineHeight: 1.6, color: 'var(--muted)', margin: 0 }}>
        Open <code style={{
          fontFamily: 'var(--mono, "JetBrains Mono", monospace)',
          background: 'color-mix(in oklab, var(--ember) 14%, transparent)',
          padding: '1px 6px', borderRadius: 4, fontSize: 13,
        }}>site/booking-modal.jsx</code> and replace the{' '}
        <code style={{
          fontFamily: 'var(--mono, "JetBrains Mono", monospace)',
          background: 'color-mix(in oklab, var(--ember) 14%, transparent)',
          padding: '1px 6px', borderRadius: 4, fontSize: 13,
        }}>{serviceKey}</code> value in{' '}
        <code style={{
          fontFamily: 'var(--mono, "JetBrains Mono", monospace)',
          background: 'color-mix(in oklab, var(--ember) 14%, transparent)',
          padding: '1px 6px', borderRadius: 4, fontSize: 13,
        }}>BOOKING_CONFIG</code> with the public URL of your Bookings service.
      </p>
      <div style={{
        padding: 16, borderRadius: 8, border: '1px dashed var(--line)',
        background: 'color-mix(in oklab, var(--ember) 4%, var(--bg))',
        fontSize: 13, lineHeight: 1.6, color: 'var(--muted)',
      }}>
        <strong style={{ color: 'var(--fg)' }}>How to get the URL:</strong><br/>
        1. Sign in at <a href="https://outlook.office.com/bookings" target="_blank" rel="noopener"
          className="hf-ulink" style={{ color: 'var(--fg)', fontWeight: 600 }}>outlook.office.com/bookings</a><br/>
        2. Open your Booking page → Services → click the service<br/>
        3. Copy the public link (looks like <code style={{ fontSize: 12 }}>https://outlook.office.com/bookwithme/user/...</code>)<br/>
        4. Paste into <code style={{ fontSize: 12 }}>BOOKING_CONFIG.{serviceKey}</code>
      </div>
      <div style={{ paddingTop: 8 }}>
        <a href="mailto:hello@hyperfocusoz.com" className="hf-ulink"
          style={{ color: 'var(--ember)', fontWeight: 600, fontSize: 14 }}>
          For now, email hello@hyperfocusoz.com →
        </a>
      </div>
    </div>
  );
}

// ---------------------------------------------------------------- //
// Mount + global API: window.openBooking(serviceId?)
// ---------------------------------------------------------------- //
(function mountBookingHost() {
  // Wait until DOM is ready
  function ensureHost() {
    let host = document.getElementById('booking-modal-root');
    if (!host) {
      host = document.createElement('div');
      host.id = 'booking-modal-root';
      document.body.appendChild(host);
    }
    return host;
  }

  let root = null;
  let openState = { open: false, serviceId: null };

  function render() {
    if (!root) {
      const host = ensureHost();
      root = ReactDOM.createRoot(host);
    }
    if (openState.open) {
      root.render(
        <BookingModal
          initialServiceId={openState.serviceId}
          onClose={() => { openState = { open: false, serviceId: null }; render(); }}
        />
      );
    } else {
      root.render(null);
    }
  }

  window.openBooking = function (serviceId) {
    openState = { open: true, serviceId: serviceId || null };
    render();
  };

  window.closeBooking = function () {
    openState = { open: false, serviceId: null };
    render();
  };

  // Intercept clicks on any element marked data-booking (or data-booking="discovery" etc.)
  document.addEventListener('click', (e) => {
    const target = e.target.closest('[data-booking]');
    if (!target) return;
    e.preventDefault();
    const id = target.getAttribute('data-booking');
    window.openBooking(id === 'true' || id === '' ? null : id);
  });
})();

})(); // end outer scope-isolation IIFE
