// ============================================================
// OSCILADOR — Servicios + Membresías (3 variantes c/u)
// ============================================================

// ── Opciones del selector de reservas (BookingOverlay) ──
const BOOKING_OPTIONS = [
  { tag: "PRÁCTICA",  title: "Práctica DJ · 1h",          price: "Bs 100",       unit: "/hora",   detail: "1 hora · CDJ-3000 × 2 + DJM-A9",              cta: "Reservar 1 hora",  href: CAL_LINKS.practicaDj1h },
  { tag: "PRÁCTICA",  title: "Práctica DJ · 2h",          price: "Bs 200",       unit: "/sesión", detail: "2 horas continuas · ideal para sets largos",   cta: "Reservar 2 horas", href: CAL_LINKS.practicaDj2h },
  { tag: "PRÁCTICA",  title: "Práctica DJ · 2 personas · 1h", price: "Bs 150",  unit: "/hora",   detail: "1 hora · 2 personas juntas · CDJ-3000 × 2 + DJM-A9", cta: "Reservar para 2", href: CAL_LINKS.practicaDj2p },
  { tag: "CLASE",     title: "Clase / Sesión guiada",     price: "Bs 250",       unit: "/hora",   detail: "1 hora con instructor, técnica y feedback",    cta: "Reservar clase",   href: CAL_LINKS.claseSesionGuiada },
  { tag: "GRABACIÓN", title: "Grabación de set + máster", price: "Bs 200",       unit: "/set",    detail: "Grabación audio profesional + mastering · máx 2h", cta: "Reservar grabación", href: CAL_LINKS.grabacionSet },
  { tag: "MEMBRESÍA", title: "Membresía / Plan mensual",  price: "Desde Bs 800", unit: "/mes",    detail: "4–20 horas por mes · reserva con prioridad",  cta: "Consultar por WhatsApp", href: "https://wa.me/59167165251?text=Hola%2C%20quiero%20consultar%20sobre%20membresías" },
];

const SERVICIOS_DATA = [
  {
    tag: "PRÁCTICA",
    bookingTag: "PRÁCTICA",
    price: "Bs 100",
    unit: "/hora",
    title: "Sala de práctica",
    body: "CDJ-3000 × 2 + DJM-A9. 1 persona Bs 100/h — 2 personas juntas Bs 150/h.",
    schedule: "LUN–VIE · 11:00–19:00",
    cta: "Reservar sala",
  },
  {
    tag: "CLASES",
    bookingTag: "CLASE",
    price: "Bs 250",
    unit: "/hora",
    title: "Clase personal",
    body: "Una hora con el instructor. Trabajás tu set en vivo, identificás lo que suena mal y lo corregís en el momento.",
    schedule: "LUN–VIE · 11:00–19:00",
    cta: "Reservar clase",
  },
  {
    tag: "GRUPO",
    bookingTag: null,
    price: "Bs 1.200",
    unit: "/mes",
    title: "Curso del Mes",
    body: "Cada mes, un instructor distinto. Grupos reducidos, cupos limitados. Precio de lanzamiento · 20% off.",
    schedule: "LUN · MIÉ · VIE — POR CONVOCATORIA",
    cta: "Consultar disponibilidad",
  },
  {
    tag: "GRABACIÓN",
    bookingTag: "GRABACIÓN",
    price: "Bs 200",
    unit: "/set",
    title: "Grabación de set",
    body: "Grabación de audio profesional de tu set + mastering. Máximo 2 horas por sesión.",
    schedule: "LUN–VIE · CON RESERVA PREVIA",
    cta: "Reservar grabación",
  },
  {
    tag: "ALQUILER",
    bookingTag: null,
    price: "Bs 2.100",
    unit: "/noche",
    title: "Equipos para evento",
    body: "Todo el equipo para tu evento. Entrega y retirada coordinada.",
    schedule: "JUE / VIE / SÁB · 20:00–03:00",
    cta: "Cotizar alquiler",
  },
];

function SvcV1Cards() {
  return (
    <section className="section" id="servicios">
      <div className="container">
        <SectionHead
          num="03 / OFERTA"
          eyebrow="LO QUE OFRECEMOS"
          title="Cinco formas de usar la sala."
          titleClass="h-3"
          sub="Reserva por hora, clases personalizadas o alquiler completo para tu evento. Sin matrícula, sin contratos largos."
        />
        <div className="svc-grid">
          {SERVICIOS_DATA.map((s, i) => (
            <Reveal delay={i * 100} key={s.tag}>
              <article className="card" style={{ height: "100%" }}>
                <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center" }}>
                  <span className="tag">{s.tag}</span>
                  <span className="mono" style={{ color: "rgba(184,184,184,0.5)" }}>0{i + 1}</span>
                </div>
                <h3 className="display" style={{ fontSize: "clamp(24px, 2.4vw, 32px)", lineHeight: 1 }}>{s.title}</h3>
                <div style={{ display: "flex", alignItems: "baseline", gap: 4 }}>
                  <span className="mono-lg" style={{ fontSize: "clamp(28px, 3vw, 40px)", color: "var(--white)" }}>{s.price}</span>
                  <span className="mono" style={{ color: "var(--silver)" }}>{s.unit}</span>
                </div>
                <p className="muted" style={{ fontSize: 15, lineHeight: 1.5, flex: 1 }}>{s.body}</p>
                <div style={{
                  display: "flex", alignItems: "center", justifyContent: "space-between",
                  gap: 16, paddingTop: 20, borderTop: "1px solid var(--line)",
                }}>
                  <span className="mono" style={{ fontSize: 10 }}>{s.schedule}</span>
                  <a
                    href="#reservar"
                    onClick={(e) => {
                      e.preventDefault();
                      if (s.bookingTag) {
                        window.dispatchEvent(new CustomEvent("openBooking", { detail: { tag: s.bookingTag } }));
                      } else {
                        window.open(`https://wa.me/59167165251?text=${encodeURIComponent("Hola, quiero consultar sobre " + s.title)}`, "_blank");
                      }
                    }}
                    className="mono"
                    style={{ color: "var(--white)", display: "inline-flex", alignItems: "center", gap: 6 }}
                  >
                    {s.cta} <Arrow size={11} />
                  </a>
                </div>
                {s.tag === "PRÁCTICA" && (
                  <p className="mono" style={{ fontSize: 10, color: "rgba(184,184,184,0.5)", marginTop: 12, textAlign: "right" }}>
                    ¿Practicas seguido?{" "}
                    <a
                      href="#membresias"
                      onClick={(e) => { e.preventDefault(); document.getElementById("membresias")?.scrollIntoView({ behavior: "smooth" }); }}
                      style={{ color: "var(--white)", textDecoration: "underline" }}
                    >
                      Ver planes →
                    </a>
                  </p>
                )}
              </article>
            </Reveal>
          ))}
        </div>
      </div>
    </section>
  );
}

function SvcV2Rows() {
  // Rider-style horizontal rows — denser, more technical
  return (
    <section className="section" id="servicios">
      <div className="container">
        <SectionHead
          num="03 / OFERTA"
          eyebrow="LO QUE OFRECEMOS"
          title="Cinco formas de usar la sala."
          titleClass="h-3"
          sub="Reserva por hora, clases personalizadas o alquiler completo para tu evento."
        />
        <div className="svc-row">
          {SERVICIOS_DATA.map((s, i) => (
            <Reveal delay={i * 80} key={s.tag}>
              <div className="svc-line">
                <span className="mono" style={{ color: "rgba(184,184,184,0.5)" }}>0{i + 1} · {s.tag}</span>
                <h3 className="svc-title">{s.title}</h3>
                <p className="muted" style={{ fontSize: 15, lineHeight: 1.5 }}>{s.body}<br/>
                  <span className="mono" style={{ fontSize: 11, color: "rgba(184,184,184,0.5)", marginTop: 6, display: "inline-block" }}>{s.schedule}</span>
                </p>
                <div style={{ display: "flex", flexDirection: "column", alignItems: "flex-start", gap: 8 }}>
                  <span className="svc-price">{s.price}<span className="unit">{s.unit}</span></span>
                  <a href="#reservar" onClick={(e) => { e.preventDefault(); window.dispatchEvent(new Event("openBooking")); }} className="mono" style={{ color: "var(--white)", display: "inline-flex", alignItems: "center", gap: 6 }}>
                    Reservar <Arrow size={11} />
                  </a>
                </div>
              </div>
            </Reveal>
          ))}
        </div>
      </div>
    </section>
  );
}

function SvcV3Numbered() {
  // Numbered minimal: huge prices, sparse type
  return (
    <section className="section" id="servicios">
      <div className="container">
        <SectionHead
          num="03 / OFERTA"
          eyebrow="LO QUE OFRECEMOS"
          title="Cinco formas de usar la sala."
          titleClass="h-3"
          sub="Reserva por hora, clases personalizadas o alquiler completo para tu evento."
        />
        <div style={{ display: "grid", gap: 0 }}>
          {SERVICIOS_DATA.map((s, i) => (
            <Reveal delay={i * 100} key={s.tag}>
              <div style={{
                padding: "clamp(28px, 4vw, 56px) 0",
                borderTop: "1px solid var(--line)",
                borderBottom: i === SERVICIOS_DATA.length - 1 ? "1px solid var(--line)" : "0",
                display: "grid",
                gridTemplateColumns: "1fr",
                gap: 32,
              }}
              className="svc-num-row">
                <div>
                  <span className="mono" style={{ color: "rgba(184,184,184,0.5)" }}>0{i + 1}</span>
                  <h3 className="display" style={{ fontSize: "clamp(36px, 5vw, 64px)", lineHeight: 0.95, marginTop: 14 }}>
                    {s.title}
                  </h3>
                  <p className="muted" style={{ marginTop: 18, fontSize: 16, maxWidth: "44ch", lineHeight: 1.5 }}>{s.body}</p>
                </div>
                <div style={{ display: "flex", flexDirection: "column", justifyContent: "space-between", gap: 24 }}>
                  <span style={{
                    fontFamily: "var(--font-mono)",
                    fontSize: "clamp(48px, 6vw, 84px)",
                    lineHeight: 1, color: "var(--white)",
                    letterSpacing: "-0.02em",
                  }}>
                    {s.price}<span style={{ color: "var(--silver)", fontSize: "0.42em", letterSpacing: "0.06em" }}>{s.unit}</span>
                  </span>
                  <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", gap: 16, flexWrap: "wrap" }}>
                    <span className="mono" style={{ fontSize: 11 }}>{s.schedule}</span>
                    <a href="#reservar" onClick={(e) => { e.preventDefault(); window.dispatchEvent(new Event("openBooking")); }} className="btn btn-ghost" style={{ height: 44, padding: "0 18px" }}>
                      {s.cta}
                      <Arrow size={12} />
                    </a>
                  </div>
                </div>
              </div>
            </Reveal>
          ))}
        </div>
        <style>{`
          @media (min-width: 880px) {
            .svc-num-row { grid-template-columns: 1.2fr 1fr; gap: 80px; align-items: start; }
          }
        `}</style>
      </div>
    </section>
  );
}

function Servicios({ variant }) {
  if (variant === "rows") return <SvcV2Rows />;
  if (variant === "numbered") return <SvcV3Numbered />;
  return <SvcV1Cards />;
}

// ============================================================
// MEMBRESÍAS
// ============================================================

const MEMBERSHIP_DATA = [
  {
    tag: "STARTER",
    price: "Bs 800",
    unit: "/mes",
    desc: "4 clases personales por mes.",
    bullets: [
      "4× clases 1 a 1 (1h c/u)",
      "Acceso a sala con instructor",
      "Cancela cuando quieras",
    ],
  },
  {
    tag: "BUILDER",
    price: "Bs 1.000",
    unit: "/mes",
    desc: "2 clases + 8 horas de sala por mes.",
    featured: true,
    bullets: [
      "2× clases personales (1h c/u)",
      "8h de sala libre por mes",
      "Reserva con prioridad",
      "20% off el primer mes en sala",
    ],
  },
  {
    tag: "RESIDENTE",
    price: "Bs 1.500",
    unit: "/mes",
    desc: "20 horas de sala por mes.",
    bullets: [
      "20h de sala libre por mes",
      "Reserva con prioridad",
      "Acceso a horarios extendidos",
    ],
  },
];

function MemCard({ plan, i }) {
  return (
    <article className={`card ${plan.featured ? "featured" : ""}`} style={{ position: "relative", height: "100%", width: "100%" }}>
      {plan.featured && (
        <div style={{
          position: "absolute", top: -1, right: -1,
          background: "var(--white)", color: "var(--black)",
          fontFamily: "var(--font-mono)", fontSize: 10,
          letterSpacing: "0.18em", textTransform: "uppercase",
          padding: "6px 10px",
        }}>
          MÁS ELEGIDO
        </div>
      )}
      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center" }}>
        <span className="tag">{plan.tag}</span>
        <span className="mono" style={{ color: "rgba(184,184,184,0.5)" }}>0{i + 1}/03</span>
      </div>
      <div style={{ display: "flex", alignItems: "baseline", gap: 4, marginTop: 4 }}>
        <span style={{
          fontFamily: "var(--font-mono)", fontSize: "clamp(36px, 4vw, 56px)",
          color: "var(--white)", lineHeight: 1, letterSpacing: "-0.02em",
        }}>{plan.price}</span>
        <span className="mono" style={{ color: "var(--silver)" }}>{plan.unit}</span>
      </div>
      <p style={{ fontSize: 16, color: "var(--white)", fontWeight: 500, lineHeight: 1.35 }}>{plan.desc}</p>
      <ul style={{ listStyle: "none", display: "flex", flexDirection: "column", gap: 10, padding: 0, flex: 1 }}>
        {plan.bullets.map((b) => (
          <li key={b} style={{ display: "flex", gap: 12, fontSize: 14, color: "var(--silver)", lineHeight: 1.4 }}>
            <span className="mono" style={{ color: "var(--white)", flex: "none", marginTop: 1 }}>—</span>
            <span>{b}</span>
          </li>
        ))}
      </ul>
      <a href={`https://wa.me/59167165251?text=${encodeURIComponent("Hola, quiero consultar sobre la membresía " + plan.tag)}`} target="_blank" rel="noopener" className={`btn ${plan.featured ? "btn-signal" : "btn-ghost"}`} style={{ marginTop: "auto" }}>
        Consultar {plan.tag}
        <Arrow size={12} />
      </a>
    </article>
  );
}

function MemV1Grid() {
  return (
    <section className="section" id="membresias">
      <div className="container">
        <SectionHead
          num="04 / MEMBRESÍAS"
          eyebrow="PLANES MENSUALES"
          title="Pertenece a la sala."
          titleClass="h-3"
          sub="Cupos limitados — sujeto a disponibilidad. Cada persona necesita su propia membresía."
        />
        <div className="mem-grid">
          {MEMBERSHIP_DATA.map((plan, i) => (
            <Reveal delay={i * 100} key={plan.tag}>
              <MemCard plan={plan} i={i} />
            </Reveal>
          ))}
        </div>
      </div>
    </section>
  );
}

function MemV2Stage() {
  // BUILDER center-stage bigger
  return (
    <section className="section" id="membresias">
      <div className="container">
        <SectionHead
          num="04 / MEMBRESÍAS"
          eyebrow="PLANES MENSUALES"
          title="Pertenece a la sala."
          titleClass="h-3"
          sub="Cupos limitados — sujeto a disponibilidad. Cada persona necesita su propia membresía."
        />
        <div className="mem-grid" style={{ alignItems: "stretch" }}>
          {MEMBERSHIP_DATA.map((plan, i) => (
            <Reveal delay={i * 100} key={plan.tag} style={{ display: "flex" }}>
              <div style={{
                width: "100%",
                transform: plan.featured ? "translateY(-12px)" : "none",
                display: "block",
              }}>
                <MemCard plan={plan} i={i} />
              </div>
            </Reveal>
          ))}
        </div>
      </div>
    </section>
  );
}

function MemV3Table() {
  // Comparison-table rider
  return (
    <section className="section" id="membresias">
      <div className="container">
        <SectionHead
          num="04 / MEMBRESÍAS"
          eyebrow="PLANES MENSUALES"
          title="Pertenece a la sala."
          titleClass="h-3"
          sub="Cupos limitados — sujeto a disponibilidad. Cada persona necesita su propia membresía."
        />
        <div className="mem-table-wrap">
          <div className="mem-table">
            <div className="mem-thead">
              <div className="mem-th">{/* spec col */}</div>
              {MEMBERSHIP_DATA.map((p) => (
                <div className={`mem-th ${p.featured ? "feat" : ""}`} key={p.tag}>
                  <span className="tag" style={{ marginBottom: 12 }}>{p.tag}</span>
                  {p.featured && <span className="tag solid" style={{ marginLeft: 8 }}>MÁS ELEGIDO</span>}
                  <div style={{
                    fontFamily: "var(--font-mono)", fontSize: 36, color: "var(--white)",
                    lineHeight: 1, marginTop: 14, letterSpacing: "-0.02em",
                  }}>
                    {p.price}<span style={{ fontSize: 14, color: "var(--silver)", letterSpacing: "0.06em" }}>{p.unit}</span>
                  </div>
                  <div className="muted" style={{ marginTop: 12, fontSize: 13, lineHeight: 1.4 }}>{p.desc}</div>
                </div>
              ))}
            </div>
            {["Clases personales", "Horas de sala", "Reserva prioritaria", "Cupo"].map((row, ri) => (
              <Reveal delay={ri * 60} key={row}>
                <div className="mem-tr">
                  <div className="mem-td mono">{row}</div>
                  {MEMBERSHIP_DATA.map((p) => {
                    let v = "—";
                    if (row === "Clases personales") v = p.tag === "STARTER" ? "4 / mes" : p.tag === "BUILDER" ? "2 / mes" : "—";
                    if (row === "Horas de sala") v = p.tag === "STARTER" ? "—" : p.tag === "BUILDER" ? "8h / mes" : "20h / mes";
                    if (row === "Reserva prioritaria") v = p.tag === "STARTER" ? "—" : "Sí";
                    if (row === "Cupo") v = "Limitado";
                    return (
                      <div className={`mem-td ${p.featured ? "feat" : ""}`} key={p.tag}>
                        <span className={v === "—" ? "muted" : ""} style={{ fontFamily: "var(--font-mono)", fontSize: 14 }}>{v}</span>
                      </div>
                    );
                  })}
                </div>
              </Reveal>
            ))}
            <div className="mem-tr mem-cta-row">
              <div className="mem-td"></div>
              {MEMBERSHIP_DATA.map((p) => (
                <div className={`mem-td ${p.featured ? "feat" : ""}`} key={p.tag}>
                  <a href={`https://wa.me/59167165251?text=${encodeURIComponent("Hola, quiero consultar sobre la membresía " + p.tag)}`} target="_blank" rel="noopener" className={`btn ${p.featured ? "btn-signal" : "btn-ghost"}`} style={{ width: "100%", height: 46 }}>
                    Consultar
                  </a>
                </div>
              ))}
            </div>
          </div>
        </div>
        <style>{`
          .mem-table-wrap { overflow-x: auto; }
          .mem-table { min-width: 760px; }
          .mem-thead, .mem-tr {
            display: grid;
            grid-template-columns: 1.2fr 1fr 1.2fr 1fr;
            border-top: 1px solid var(--line);
          }
          .mem-thead { border-top: 0; border-bottom: 1px solid var(--line); padding-bottom: 32px; padding-top: 16px; }
          .mem-th, .mem-td { padding: 18px 20px; }
          .mem-th.feat, .mem-td.feat { background: var(--graphite); }
          .mem-cta-row { border-bottom: 1px solid var(--line); padding: 16px 0; }
        `}</style>
      </div>
    </section>
  );
}

function Membresias({ variant }) {
  if (variant === "stage") return <MemV2Stage />;
  if (variant === "table") return <MemV3Table />;
  return <MemV1Grid />;
}

// ============================================================
// BOOKING OVERLAY — Selector de reservas (CLA-37 + CLA-38)
// ============================================================
function CalBookingPanel({ opt, onClose, onBack }) {
  const [bookingData, setBookingData] = React.useState(null);

  React.useEffect(() => {
    function handleMessage(e) {
      try {
        if (!e.origin.includes("cal.com")) return;
        const msg = typeof e.data === "string" ? JSON.parse(e.data) : e.data;
        if (!msg) return;
        console.log("[Cal.com postMessage]", msg.type || msg.action || "(sin type)", msg);

        const msgType = (msg.type || msg.action || "").toLowerCase();
        const isBooking = msgType === "bookingsuccessful" || msgType === "bookingsuccessfulv2";
        if (!isBooking) return;

        const booking = msg?.data?.booking || msg?.data || {};
        console.log("[Cal booking object COMPLETO]", JSON.stringify(msg.data));
        const startTime =
          booking.startTime || booking.start_time || booking.startAt ||
          booking.start || msg?.data?.startTime || msg?.data?.start_time || "";
        let formattedTime = "";
        if (startTime) {
          try {
            formattedTime = new Date(startTime).toLocaleString("es-419", {
              weekday: "long", day: "numeric", month: "long",
              hour: "2-digit", minute: "2-digit",
            });
          } catch (_) { formattedTime = startTime; }
        }
        const waText = formattedTime
          ? `Hola, acabo de reservar ${opt.title} en Oscilador Academy para el ${formattedTime}. ¿Me enviás el QR de pago?`
          : `Hola, acabo de reservar ${opt.title} en Oscilador Academy. ¿Me enviás el QR de pago?`;
        setBookingData({ formattedTime, waText });
      } catch (_) {}
    }
    window.addEventListener("message", handleMessage);
    return () => window.removeEventListener("message", handleMessage);
  }, []);

  const embedUrl = `${opt.href}?embed=true&layout=month_view`;
  const fallbackWaText = `Hola, acabo de reservar ${opt.title} en Oscilador. ¿Me enviás el QR de pago?`;

  if (bookingData) {
    return (
      <div className="bk-overlay" role="dialog" aria-modal="true" onClick={onClose}>
        <div className="bk-panel" onClick={(e) => e.stopPropagation()}>
          <div className="bk-header">
            <div>
              <div className="eyebrow">
                <span style={{ color: "rgba(184,184,184,0.5)" }}>RESERVA</span>
                <span style={{ color: "var(--signal)" }}>CONFIRMADA ✓</span>
              </div>
              <h2 className="display" style={{ fontSize: "clamp(22px, 3vw, 38px)", marginTop: 12 }}>
                {opt.title}
              </h2>
              {bookingData.formattedTime && (
                <p className="mono" style={{ marginTop: 8, color: "var(--white)", fontSize: 13, textTransform: "capitalize" }}>
                  {bookingData.formattedTime}
                </p>
              )}
            </div>
            <button className="bk-close" onClick={onClose} aria-label="Cerrar">✕</button>
          </div>
          <div className="bk-disclaimer">
            <p style={{ fontSize: 15, color: "var(--silver)", lineHeight: 1.55, margin: 0 }}>
              Tu hora quedó en el calendario. Ahora confirmá el cupo enviando este mensaje — te mandamos el QR de pago.
            </p>
          </div>
          <div style={{ padding: "20px clamp(20px,3vw,36px) 8px" }}>
            <a
              href={`https://wa.me/59167165251?text=${encodeURIComponent(bookingData.waText)}`}
              target="_blank"
              rel="noopener"
              className="btn btn-signal"
              style={{ width: "100%", justifyContent: "center", height: 54, fontSize: 16, gap: 10 }}
              onClick={onClose}
            >
              <WhatsAppIcon size={20} />
              Confirmar por WhatsApp
              <Arrow size={14} />
            </a>
          </div>
          <div className="bk-footer">
            <span className="mono" style={{ fontSize: 10 }}>
              QR O TRANSFERENCIA · CONFIRMACIÓN EN MENOS DE 24H
            </span>
          </div>
        </div>
      </div>
    );
  }

  return (
    <div className="bk-overlay" role="dialog" aria-modal="true" onClick={onClose}>
      <div className="bk-panel bk-panel--embed" onClick={(e) => e.stopPropagation()}>

        <div className="bk-header">
          <div>
            <div className="eyebrow">
              <span style={{ color: "rgba(184,184,184,0.5)" }}>RESERVAR</span>
              <span>{opt.tag}</span>
            </div>
            <h2 className="display" style={{ fontSize: "clamp(20px, 2.5vw, 32px)", marginTop: 8 }}>
              {opt.title}
              <span style={{ color: "var(--silver)", fontWeight: 400, fontSize: "0.75em", marginLeft: 10 }}>{opt.price}</span>
            </h2>
          </div>
          <button className="bk-close" onClick={onClose} aria-label="Cerrar">✕</button>
        </div>

        <iframe
          src={embedUrl}
          className="bk-cal-embed"
          title={`Reservar ${opt.title}`}
          allow="payment"
        />

        <div className="bk-embed-footer">
          <button
            onClick={onBack}
            style={{ background: "none", border: "none", color: "var(--silver)", cursor: "pointer",
                     fontFamily: "var(--font-mono)", fontSize: 10, letterSpacing: "0.08em", padding: 0 }}
          >
            ← VOLVER
          </button>
          <a
            href={`https://wa.me/59167165251?text=${encodeURIComponent(fallbackWaText)}`}
            target="_blank"
            rel="noopener"
            style={{ fontFamily: "var(--font-mono)", fontSize: 10, color: "var(--silver)", textDecoration: "none", textAlign: "right", letterSpacing: "0.06em" }}
          >
            ¿YA RESERVASTE? → WHATSAPP
          </a>
        </div>

      </div>
    </div>
  );
}

function BookingOverlay() {
  const [open, setOpen] = React.useState(false);
  const [selectedOpt, setSelectedOpt] = React.useState(null);
  const [filteredOptions, setFilteredOptions] = React.useState(null);

  React.useEffect(() => {
    const handler = (e) => {
      setOpen(true);
      const tag = e.detail?.tag;
      if (tag) {
        const filtered = BOOKING_OPTIONS.filter(o => o.tag === tag);
        if (filtered.length === 1) {
          setSelectedOpt(filtered[0]);
        } else if (filtered.length > 1) {
          setFilteredOptions(filtered);
        }
      }
    };
    window.addEventListener("openBooking", handler);
    return () => window.removeEventListener("openBooking", handler);
  }, []);

  React.useEffect(() => {
    document.body.style.overflow = open ? "hidden" : "";
    return () => { document.body.style.overflow = ""; };
  }, [open]);

  function handleClose() { setOpen(false); setSelectedOpt(null); setFilteredOptions(null); }

  if (!open) return null;

  if (selectedOpt) {
    return (
      <CalBookingPanel
        opt={selectedOpt}
        onClose={handleClose}
        onBack={() => setSelectedOpt(null)}
      />
    );
  }

  return (
    <div className="bk-overlay" role="dialog" aria-modal="true" onClick={handleClose}>
      <div className="bk-panel" onClick={(e) => e.stopPropagation()}>

        <div className="bk-header">
          <div>
            <div className="eyebrow">
              <span style={{ color: "rgba(184,184,184,0.5)" }}>RESERVAS</span>
              <span>ELIGE TU SERVICIO</span>
            </div>
            <h2 className="display" style={{ fontSize: "clamp(24px, 3.5vw, 44px)", marginTop: 12 }}>
              ¿Qué quieres reservar?
            </h2>
          </div>
          <button className="bk-close" onClick={handleClose} aria-label="Cerrar">✕</button>
        </div>

        <div className="bk-disclaimer">
          <span className="mono" style={{ fontSize: 10, color: "var(--signal)" }}>IMPORTANTE · LEER ANTES DE CONTINUAR</span>
          <p style={{ fontSize: 13, color: "var(--silver)", lineHeight: 1.55, marginTop: 8 }}>
            La solicitud <strong style={{ color: "var(--white)" }}>no confirma el cupo</strong>.
            El cupo queda confirmado solo después de validar el pago por QR o transferencia.
            Oscilador te enviará los datos por WhatsApp. No hay pago por tarjeta en la web.
          </p>
        </div>

        <div className="bk-cards">
          {(filteredOptions ?? BOOKING_OPTIONS).map((opt) => (
            <a
              key={opt.title}
              href={opt.href}
              onClick={(e) => { e.preventDefault(); setSelectedOpt(opt); }}
              className="bk-card"
            >
              <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-start", gap: 12 }}>
                <span className="tag">{opt.tag}</span>
                <span style={{ fontFamily: "var(--font-mono)", fontSize: "clamp(16px, 2vw, 22px)", color: "var(--white)", letterSpacing: "-0.02em", lineHeight: 1 }}>{opt.price}</span>
              </div>
              <div style={{ flex: 1, marginTop: 12 }}>
                <h3 className="display" style={{ fontSize: "clamp(17px, 2vw, 24px)", lineHeight: 1 }}>{opt.title}</h3>
                <p className="muted" style={{ fontSize: 13, marginTop: 8, lineHeight: 1.5 }}>{opt.detail}</p>
              </div>
              <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", gap: 8, paddingTop: 14, borderTop: "1px solid var(--line)", marginTop: 16 }}>
                <span className="mono" style={{ fontSize: 11 }}>{opt.cta}</span>
                <Arrow size={11} />
              </div>
            </a>
          ))}
        </div>

        <div className="bk-footer">
          <span className="mono" style={{ fontSize: 10 }}>
            CONFIRMACIÓN EN MENOS DE 24H · SIN PAGO POR TARJETA · QR VÍA WHATSAPP
          </span>
        </div>

      </div>
    </div>
  );
}

// ============================================================
// BOOKING CONFIRMED — Modal post-cal.com (detecta ?booked=1 en URL)
// ============================================================
const BOOKING_SERVICE_NAMES = {
  'practica-1h': 'Práctica DJ · 1h',
  'practica-2h': 'Práctica DJ · 2h',
  'practica-2p': 'Práctica DJ · 2 personas',
  'clase':       'Clase / Sesión guiada',
  'grabacion':   'Grabación de set',
};

function BookingConfirmed() {
  const [data, setData] = React.useState(null);

  React.useEffect(() => {
    const params = new URLSearchParams(window.location.search);
    if (params.get('booked') !== '1') return;

    const service      = params.get('service') || '';
    const timeRaw      = params.get('time')    || '';
    const name         = params.get('name')    || '';

    let formattedTime = '';
    if (timeRaw) {
      try {
        formattedTime = new Date(timeRaw).toLocaleString('es-419', {
          weekday: 'long', day: 'numeric', month: 'long',
          hour: '2-digit', minute: '2-digit',
        });
      } catch (_) {
        formattedTime = timeRaw;
      }
    }

    setData({ service, formattedTime, name });
    window.history.replaceState({}, '', window.location.pathname);
  }, []);

  if (!data) return null;

  const serviceName = BOOKING_SERVICE_NAMES[data.service] || 'tu reserva';
  const waText = data.formattedTime
    ? `Hola, reservé ${serviceName} para el ${data.formattedTime}. ¿Me enviás el QR de pago?`
    : `Hola, reservé ${serviceName} en Oscilador. ¿Me enviás el QR de pago?`;

  return (
    <div className="bk-overlay" role="dialog" aria-modal="true" onClick={() => setData(null)}>
      <div className="bk-panel" onClick={(e) => e.stopPropagation()}>

        <div className="bk-header">
          <div>
            <div className="eyebrow">
              <span style={{ color: "rgba(184,184,184,0.5)" }}>RESERVA</span>
              <span>HORA REGISTRADA</span>
            </div>
            <h2 className="display" style={{ fontSize: "clamp(22px, 3vw, 38px)", marginTop: 12 }}>
              {serviceName}
            </h2>
            {data.formattedTime && (
              <p className="mono" style={{ marginTop: 8, color: "var(--white)", fontSize: 13, textTransform: "capitalize" }}>
                {data.formattedTime}
              </p>
            )}
          </div>
          <button className="bk-close" onClick={() => setData(null)} aria-label="Cerrar">✕</button>
        </div>

        <div className="bk-disclaimer">
          <p style={{ fontSize: 15, color: "var(--silver)", lineHeight: 1.55, margin: 0 }}>
            Tu hora quedó en el calendario. Escríbenos por WhatsApp y te mandamos el QR.
          </p>
        </div>

        <div style={{ padding: "20px 24px 8px" }}>
          <a
            href={`https://wa.me/59167165251?text=${encodeURIComponent(waText)}`}
            target="_blank"
            rel="noopener"
            className="btn btn-signal"
            style={{ width: "100%", justifyContent: "center", height: 54, fontSize: 16, gap: 10 }}
          >
            <WhatsAppIcon size={20} />
            Enviar mensaje
            <Arrow size={14} />
          </a>
        </div>

        <div className="bk-footer">
          <span className="mono" style={{ fontSize: 10 }}>
            QR O TRANSFERENCIA · CONFIRMACIÓN EN MENOS DE 24H
          </span>
        </div>

      </div>
    </div>
  );
}

Object.assign(window, { Servicios, Membresias, BookingOverlay, BookingConfirmed });
