// booking.jsx — Skedron embed wrapper
const { useEffect: useEffectB } = React;

const SKEDRON_SLUGS = {
  woodcreek:  "woodcreek",
  crosscreek: "cross-creek-ranch",
};

// Maps our service IDs to Skedron's service slugs.
// If a service shows wrong, update the value to match the slug in your Skedron dashboard.
const SKEDRON_SERVICES = {
  "swedish-deep-tissue":    "019c4ff7-deb4-73a1-9294-68ad86bc9e77",
  "essential-oil-prenatal": "019c4ff7-dec3-7141-8333-f66271e3018d",
  "couples-massage":        "019c4ff7-dea4-7008-b25b-ecb3a0a9b2a3",
  "face-and-head-massage":  "019c5859-aee3-7046-9b8b-7bc25016ad24",
  "combo-massage":          "019c4ff7-de91-758c-9a3c-dee6d88e87f2",
  "foot-reflexology":       "019c585b-1c3a-7144-9c5b-89943f76118f",
};

function Booking({ initialServiceId, initialDuration }) {
  const { loc } = useRoute();
  const slug     = SKEDRON_SLUGS[loc?.id];
  const service  = SKEDRON_SERVICES[initialServiceId] || null;
  const duration = initialDuration ? String(initialDuration) : null;
  const [embedFailed, setEmbedFailed] = React.useState(false);

  useEffectB(() => {
    setEmbedFailed(false);
    const existing = document.getElementById("skedron-script");
    if (existing) existing.remove();

    const script = document.createElement("script");
    script.id  = "skedron-script";
    script.src = "https://app.skedron.com/embed.js";
    document.body.appendChild(script);

    // Detect mount failure — if the embed root never gets children within 4s,
    // assume the slug is bad or Skedron is unreachable and swap in a fallback.
    const timer = setTimeout(() => {
      const root = document.querySelector("[data-skedron-booking]");
      if (root && root.childElementCount === 0) setEmbedFailed(true);
    }, 4000);

    return () => {
      clearTimeout(timer);
      const s = document.getElementById("skedron-script");
      if (s) s.remove();
    };
  }, [slug, service, duration]);

  return (
    <main style={{ background: "var(--cream)", minHeight: "60vh" }}>
      <section style={{ paddingTop: 48, paddingBottom: 32, borderBottom: "1px solid var(--line)", background: "var(--ivory)" }}>
        <div className="wrap">
          <div className="eyebrow"><span className="dot-mark"/>Book an Appointment</div>
          <h1 className="t-h1" style={{ marginTop: 10 }}>
            {loc?.name || "Healing Pearl Massage"}
          </h1>
          <p className="t-small" style={{ marginTop: 8, color: "var(--gray-500)" }}>
            {loc?.streetLine1}, {loc?.streetLine2} · <a href={"tel:" + loc?.phoneTel} style={{ color: "var(--gray-700)" }}>{loc?.phone}</a>
          </p>
        </div>
      </section>

      {/* Before-you-book trust strip */}
      <section style={{ paddingTop: 32, paddingBottom: 8 }}>
        <div className="wrap">
          <div className="trust-strip" style={{ display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: 16 }}>
            <TrustPoint
              icon={<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6"><circle cx="12" cy="12" r="10"/><polyline points="12 6 12 12 16 14"/></svg>}
              title="Arrive 10 min early"
              body="Quick intake — pressure, focus areas, anything to avoid."
            />
            <TrustPoint
              icon={<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6"><path d="M12 2 L13.5 8 L20 9 L15 13.5 L16.5 20 L12 16.5 L7.5 20 L9 13.5 L4 9 L10.5 8 Z"/></svg>}
              title="Hot stones included"
              body="Warm basalt stones with every Swedish & Deep Tissue session."
            />
            <TrustPoint
              icon={<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6"><polyline points="20 6 9 17 4 12"/></svg>}
              title="Customized pressure"
              body="Light, medium, or deep — your therapist checks in throughout."
            />
            <TrustPoint
              icon={<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6"><path d="M3 12a9 9 0 1 0 18 0 9 9 0 0 0-18 0Z"/><polyline points="9 12 12 15 16 10"/></svg>}
              title="24-hour cancellation"
              body={`Need to reschedule? Call ${loc?.phone || "us"} as early as you can.`}
            />
          </div>
        </div>
      </section>

      <section style={{ paddingTop: 16, paddingBottom: 80 }}>
        <div className="wrap">
          {slug ? (
            <>
              <div
                data-skedron-booking
                data-org="healing-pearl-massage"
                data-location={slug}
                data-color="2A1F1A"
                data-bg="F8F4ED"
                data-hide-header
                style={{ display: embedFailed ? "none" : "block" }}
                {...(service  ? { "data-service":  service  } : {})}
                {...(duration ? { "data-duration": duration } : {})}
              />
              {embedFailed && (
                <div style={{ maxWidth: 520, margin: "32px auto", padding: 32, background: "var(--ivory)", border: "1px solid var(--line)", borderRadius: 8, textAlign: "center" }}>
                  <div className="eyebrow" style={{ justifyContent: "center" }}><span className="dot-mark"/>Online booking is taking a moment</div>
                  <h2 className="t-h2" style={{ marginTop: 12, fontSize: 26 }}>Call us to book.</h2>
                  <p className="t-body" style={{ marginTop: 12, color: "var(--gray-700)" }}>
                    Our online system is slow to load right now. Give us a call and we'll get you on the books — same-day appointments usually available.
                  </p>
                  {loc?.phone && (
                    <a
                      className="btn btn-primary"
                      href={`tel:${loc.phoneTel}`}
                      style={{ marginTop: 20, display: "inline-flex", padding: "14px 28px", fontSize: 16 }}
                    >
                      Call {loc.phone}
                    </a>
                  )}
                  <div style={{ marginTop: 14 }}>
                    <a
                      className="t-small"
                      style={{ color: "var(--gray-600)", textDecoration: "underline", cursor: "pointer" }}
                      onClick={() => { setEmbedFailed(false); window.location.reload(); }}
                    >
                      Try the online booking again
                    </a>
                  </div>
                </div>
              )}
            </>
          ) : (
            <div style={{ maxWidth: 520, margin: "32px auto", padding: 32, background: "var(--ivory)", border: "1px solid var(--line)", borderRadius: 8, textAlign: "center" }}>
              <h2 className="t-h2" style={{ fontSize: 26 }}>Online booking coming soon.</h2>
              <p className="t-body" style={{ marginTop: 12, color: "var(--gray-700)" }}>
                This location isn't on online booking yet — please call to reserve.
              </p>
              {loc?.phone && (
                <a className="btn btn-primary" href={`tel:${loc.phoneTel}`} style={{ marginTop: 20, display: "inline-flex", padding: "14px 28px", fontSize: 16 }}>
                  Call {loc.phone}
                </a>
              )}
            </div>
          )}
        </div>
      </section>
    </main>
  );
}

function TrustPoint({ icon, title, body }) {
  return (
    <div className="trust-point" style={{ display: "flex", gap: 14, alignItems: "flex-start", padding: "16px 0" }}>
      <span style={{ flexShrink: 0, color: "var(--accent)", marginTop: 2 }}>{icon}</span>
      <div>
        <div className="t-small" style={{ fontWeight: 600, color: "var(--ink)", fontFamily: "var(--font-serif)", fontSize: 15 }}>{title}</div>
        <p className="t-small" style={{ margin: "4px 0 0", color: "var(--gray-600)", lineHeight: 1.55, fontSize: 13 }}>{body}</p>
      </div>
    </div>
  );
}

Object.assign(window, { Booking });
