/* booking.jsx — session chooser that hands off to Cal.com for the real
   calendar + Stripe payment + confirmation email. Exports BookingFlow to window.

   ┌─────────────────────────────────────────────────────────────────┐
   │  SET UP REAL BOOKINGS — edit the two lines marked  ◀── EDIT  below │
   └─────────────────────────────────────────────────────────────────┘
   1. Make a free account at https://cal.com
   2. Connect Stripe (Cal: Settings → Payments) so it can take payment.
   3. Create two event types and set their prices + a 60-min length:
        • "Consultation Call"      → its link becomes  cal.com/<you>/consultation-call
        • "Audit & Strategy Call"  → its link becomes  cal.com/<you>/audit-strategy-call
   4. Cap total bookings: Cal → Availability/Limits → 3 bookings per week.
   5. Put your Cal.com username below. That's it — the buttons go live.

   Until CAL_USERNAME is filled in, the buttons safely open the visitor's
   email to you instead (so nothing is ever fake or broken).
*/
const CAL_USERNAME = "roan-davies"; // ◀── EDIT: your cal.com username, e.g. "roan"
const OWNER_EMAIL  = "roandavies2@gmail.com"; // ◀── EDIT: where booking emails should go if Cal isn't set up yet

const CAL_SLUGS = { call: "consultation-call", audit: "audit-strategy-call" };
const CAL_READY = CAL_USERNAME !== "YOUR-CAL-USERNAME";

/* Scarcity badges shown on the booking screen ("Only N spots left" / "Sold out").
   These are numbers YOU set by hand — update them as your week fills up. Cal.com
   still enforces the real 3-per-week cap on its side. Set a value to 0 to show
   "Sold out" for that session. */
const SPOTS = { call: 1, audit: 1 }; // ◀── EDIT these as the week fills

const { useEffect: useEffectB } = React;

function BookingFlow({ open, onClose, callRate = 200, auditRate = 400, theme = "dark" }) {
  const PLANS = [
    {
      id: "call",
      name: "Consultation Call",
      price: callRate,
      meta: "60-min live call",
      left: SPOTS.call,
      desc: "A focused hour on one or two problems: packaging, strategy, direction. With time for your questions.",
    },
    {
      id: "audit",
      name: "Audit & Strategy Call",
      price: auditRate,
      meta: "Channel audit + 60-min call",
      left: SPOTS.audit,
      desc: "I review your channel, packaging and a few of your videos beforehand, then we spend an hour building a clear plan — with written notes after.",
    },
  ];
  const allSold = PLANS.every((p) => p.left <= 0);

  // lock body scroll while open
  useEffectB(() => {
    document.body.style.overflow = open ? "hidden" : "";
    return () => { document.body.style.overflow = ""; };
  }, [open]);

  // esc to close
  useEffectB(() => {
    const h = (e) => { if (e.key === "Escape" && open) onClose(); };
    window.addEventListener("keydown", h);
    return () => window.removeEventListener("keydown", h);
  }, [open, onClose]);

  function choosePlan(p) {
    if (p.left <= 0) return; // sold out — do nothing
    if (CAL_READY && window.Cal) {
      // Close our overlay; the Cal.com popup (wired via data-cal-link) takes over.
      onClose();
      return;
    }
    // Cal.com not set up yet → fall back to a real email so the button still works.
    const subject = `Booking enquiry — ${p.name}`;
    window.location.href = `mailto:${OWNER_EMAIL}?subject=${encodeURIComponent(subject)}`;
  }

  return (
    <div className={"bk-overlay" + (open ? " open" : "")} role="dialog" aria-modal="true" aria-label="Book a consultation">
      <div className="bk-scrim" onClick={onClose}></div>
      <div className="bk-panel">
        {/* summary rail */}
        <aside className="bk-rail">
          <div className="bk-rail-top">
            <div className="nav-logo"><span className="mark" aria-hidden="true"></span></div>
            <p className="bk-rail-title h3">Work with Roan</p>
            <p className="bk-rail-sub muted">Pick a session — you'll choose a time and pay securely on the next screen.</p>
          </div>
          <div className="bk-summary">
            <SummaryRow label="With" value="Roan · Google Meet" active />
            <SummaryRow label="Each week" value="Only 3 sessions" active />
            <p className="bk-rail-fine faint">Calendar &amp; secure payment handled by Cal.com + Stripe.</p>
          </div>
        </aside>

        {/* main */}
        <div className="bk-main">
          <div className="bk-head">
            <span />
            <button className="bk-close" onClick={onClose} aria-label="Close">✕</button>
          </div>

          <div className="bk-body">
            <Step title="Choose your session" sub="A focused call — or a deeper audit with a plan.">
              <p className="bk-cap-note">
                {allSold
                  ? <React.Fragment><strong>Fully booked this week.</strong> New spots open every Monday.</React.Fragment>
                  : <React.Fragment>I only take <strong>3 consultations a week</strong> — spots are limited.</React.Fragment>}
              </p>
              <div className="dur-grid">
                {PLANS.map((p) => {
                  const sold = p.left <= 0;
                  const calAttrs = (CAL_READY && !sold)
                    ? { "data-cal-link": `${CAL_USERNAME}/${CAL_SLUGS[p.id]}`, "data-cal-config": `{"theme":"${theme === "light" ? "light" : "dark"}"}` }
                    : {};
                  return (
                    <button key={p.id} className={"dur-card" + (sold ? " sold" : "")} onClick={() => choosePlan(p)} disabled={sold} aria-disabled={sold} {...calAttrs}>
                      {sold
                        ? <span className="dur-badge dur-badge--sold">Sold out</span>
                        : <span className={"dur-badge dur-badge--" + (p.left >= 3 ? "green" : p.left === 2 ? "amber" : "red")}>Only {p.left} spot{p.left > 1 ? "s" : ""} left</span>}
                      <span className="dur-name">{p.name}</span>
                      <span className="dur-meta faint">{p.meta}</span>
                      <span className="dur-price tnum">${p.price}</span>
                      <span className="dur-desc faint">{p.desc}</span>
                      {!sold && <span className="dur-cta">Choose a time <span className="arrow">↗</span></span>}
                    </button>
                  );
                })}
              </div>
            </Step>
          </div>
        </div>
      </div>
    </div>
  );
}

function Step({ title, sub, children }) {
  return (
    <div className="step">
      <h2 className="h3 step-title">{title}</h2>
      {sub && <p className="muted step-sub">{sub}</p>}
      <div className="step-content">{children}</div>
    </div>
  );
}

function SummaryRow({ label, value, active }) {
  return (
    <div className={"sum-row" + (active ? " active" : "")}>
      <span className="sum-label faint">{label}</span>
      <span className="sum-value">{value}</span>
    </div>
  );
}

Object.assign(window, { BookingFlow });
