// BookingFlow component for Heartistry Stays
// 3-step flow: dates → guest info → confirm
// Styled with cream/forest/sage/gold palette

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

// Calendar component
function Calendar({ range, setRange, blockedSet, property }) {
  const [month, setMonth] = useState(new Date().getMonth());
  const [year, setYear] = useState(new Date().getFullYear());

  const monthNames = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
  const formatDate = (d) => d.toLocaleDateString("en-IN", { day: "numeric", month: "short", year: "numeric" });

  const today = new Date();
  today.setHours(0, 0, 0, 0);

  const isDateBlocked = (date) => date < today || blockedSet.has(window.toLocalYMD(date));

  const rangeContainsBlocked = (from, to) => {
    const cursor = new Date(from);
    cursor.setDate(cursor.getDate() + 1);
    while (cursor < to) {
      if (blockedSet.has(window.toLocalYMD(cursor))) return true;
      cursor.setDate(cursor.getDate() + 1);
    }
    return false;
  };

  const handleSelectDate = (d) => {
    const date = new Date(year, month, d);
    if (isDateBlocked(date)) return;
    if (!range?.from || (range?.from && range?.to)) {
      setRange({ from: date, to: null });
    } else if (!range?.to && date > range.from) {
      if (rangeContainsBlocked(range.from, date)) {
        // Range passes through blocked dates — reset and start fresh from this date
        setRange({ from: date, to: null });
      } else {
        setRange({ from: range.from, to: date });
      }
    }
  };

  const firstDay = new Date(year, month, 1).getDay();
  const daysInMonth = new Date(year, month + 1, 0).getDate();

  const days = [];
  for (let i = 0; i < firstDay; i++) days.push(null);
  for (let d = 1; d <= daysInMonth; d++) days.push(d);

  return (
    <div style={{ marginBottom: "0.75rem" }}>
      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: "0.5rem" }}>
        <button onClick={() => setMonth(m => m === 0 ? 11 : m - 1)} style={{ background: "none", border: "none", fontSize: "18px", cursor: "pointer", color: "#71796e", padding: "4px 8px" }}>‹</button>
        <span style={{ fontSize: "13px", fontWeight: "bold", color: "#2a3d30" }}>{monthNames[month]} {year}</span>
        <button onClick={() => setMonth(m => m === 11 ? 0 : m + 1)} style={{ background: "none", border: "none", fontSize: "18px", cursor: "pointer", color: "#71796e", padding: "4px 8px" }}>›</button>
      </div>

      <div style={{ display: "grid", gridTemplateColumns: "repeat(7, 1fr)", gap: "3px", marginBottom: "3px" }}>
        {["Su", "Mo", "Tu", "We", "Th", "Fr", "Sa"].map(d => (
          <div key={d} style={{ textAlign: "center", fontSize: "10px", fontWeight: "bold", color: "#71796e", padding: "0.2rem 0" }}>{d}</div>
        ))}
      </div>

      <div style={{ display: "grid", gridTemplateColumns: "repeat(7, 1fr)", gap: "3px", marginBottom: "0.75rem" }}>
        {days.map((d, idx) => {
          if (d === null) return <div key={`empty-${idx}`} style={{ height: "34px" }} />;

          const date = new Date(year, month, d);
          const blocked = isDateBlocked(date);
          const ymd = window.toLocalYMD(date);
          const isCheckIn = range?.from && window.toLocalYMD(range.from) === ymd;
          const isCheckOut = range?.to && window.toLocalYMD(range.to) === ymd;
          const inRange = range?.from && range?.to && date > range.from && date < range.to;

          return (
            <button
              key={d}
              onClick={() => handleSelectDate(d)}
              disabled={blocked}
              style={{
                height: "34px",
                border: `1px solid ${isCheckIn || isCheckOut ? "#b18952" : "#cec1a8"}`,
                backgroundColor: isCheckIn || isCheckOut ? "#b18952" : inRange ? "#e8dccb" : blocked ? "#cec1a8" : "#faf2e8",
                color: isCheckIn || isCheckOut ? "#faf2e8" : "#2a3d30",
                borderRadius: "4px",
                cursor: blocked ? "not-allowed" : "pointer",
                fontSize: "12px",
                fontWeight: isCheckIn || isCheckOut ? "bold" : "normal",
                opacity: blocked ? 0.4 : 1,
                padding: 0,
              }}
            >
              {d}
            </button>
          );
        })}
      </div>

      {range?.from && range?.to && (
        <div style={{ padding: "0.6rem 0.75rem", backgroundColor: "rgba(250, 242, 232, 0.6)", border: "1px solid #cec1a8", borderRadius: "4px" }}>
          <div style={{ display: "flex", justifyContent: "space-between", fontSize: "13px", marginBottom: "0.2rem" }}>
            <span style={{ color: "#71796e" }}>{formatDate(range.from)} → {formatDate(range.to)}</span>
            <span style={{ fontWeight: "bold", color: "#71796e" }}>{window.nightsBetween(range.from, range.to)}n</span>
          </div>
          <div style={{ display: "flex", justifyContent: "space-between", fontSize: "12px", color: "#71796e" }}>
            <span>Total: ₹{window.nightsBetween(range.from, range.to) * property.price_per_night}</span>
          </div>
        </div>
      )}
    </div>
  );
}

function BookingFlow({ property, token, onClose }) {
  const [step, setStep] = useState("dates");
  const [range, setRange] = useState(null);
  const [guest, setGuest] = useState({ name: "", phone: "", email: "" });
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState(null);
  const [result, setResult] = useState(null);
  const [blockedSet, setBlockedSet] = useState(new Set());
  const [codeInput, setCodeInput] = useState("");
  const [codeError, setCodeError] = useState(null);
  const [confirmLoading, setConfirmLoading] = useState(false);
  const [showExitPrompt, setShowExitPrompt] = useState(false);

  const criticalSteps = ["info", "confirm", "paying"];

  const tryExit = () => {
    if (criticalSteps.includes(step)) {
      setShowExitPrompt(true);
    } else {
      onClose();
    }
  };

  // Expose tryExit globally so the click-outside handler in app.js can call it
  useEffect(() => { window._triggerExitPrompt = tryExit; }, [step]);
  useEffect(() => () => { window._triggerExitPrompt = null; }, []);

  // Load property availability
  useEffect(() => {
    if (token) {
      window.fetchPropertyInfo(token)
        .then(info => {
          setBlockedSet(window.buildBlockedDateSet(info.blocked_ranges || []));
        })
        .catch(e => setError(e.message));
    }
  }, [token]);

  const nights = range?.from && range?.to ? window.nightsBetween(range.from, range.to) : 0;
  const baseTotal = nights * property.price_per_night;
  const advanceAmount = Math.ceil(baseTotal * 0.5);

  const canProceedFromDates = range?.from && range?.to && nights >= (property.min_nights ?? 1);
  const canProceedFromInfo =
    guest.name.trim().length >= 2 &&
    (guest.phone.trim().length >= 10 || guest.email.trim().includes("@"));

  const handleBook = useCallback(async () => {
    if (!range?.from || !range?.to) return;
    setLoading(true);
    setError(null);
    try {
      const res = await window.createBooking({
        property_token: token,
        check_in: window.toLocalYMD(range.from),
        check_out: window.toLocalYMD(range.to),
        guest_name: guest.name.trim(),
        guest_phone: guest.phone.trim() || undefined,
        guest_email: guest.email.trim() || undefined,
        advance_percentage: 50,
      });
      setResult(res);
      if (res.payment_url) {
        window.open(res.payment_url, "_blank", "noopener,noreferrer");
        setStep("paying");
      } else {
        setStep("done");
      }
    } catch (e) {
      setError(e.message ?? "Something went wrong. Please try again.");
    } finally {
      setLoading(false);
    }
  }, [range, guest, token]);

  const formatDate = (d) =>
    d.toLocaleDateString("en-IN", { day: "numeric", month: "short", year: "numeric" });

  const formatINR = (n) =>
    new Intl.NumberFormat("en-IN", {
      style: "currency",
      currency: "INR",
      maximumFractionDigits: 0,
    }).format(n);

  const isDateBlocked = (date) => {
    const today = new Date();
    today.setHours(0, 0, 0, 0);
    const ymd = window.toLocalYMD(date);
    return date < today || blockedSet.has(ymd);
  };

  return (
    <div style={{ fontFamily: '"JetBrains Mono", monospace', color: "#2a3d30", padding: "18px 24px 24px", position: "relative" }}>

      {/* Exit confirmation prompt */}
      {showExitPrompt && (
        <div style={{ position: "absolute", inset: 0, background: "rgba(42,61,48,0.75)", display: "flex", alignItems: "center", justifyContent: "center", borderRadius: "18px", zIndex: 10 }}>
          <div style={{ background: "#faf2e8", padding: "1.75rem", borderRadius: "12px", textAlign: "center", maxWidth: "260px", boxShadow: "0 12px 40px rgba(42,61,48,0.3)" }}>
            <p style={{ fontSize: "14px", color: "#2a3d30", marginBottom: "0.5rem", fontWeight: "bold" }}>Exit the booking?</p>
            <p style={{ fontSize: "12px", color: "#71796e", marginBottom: "1.5rem", lineHeight: "1.5" }}>Your progress will be lost.</p>
            <div style={{ display: "flex", gap: "0.75rem" }}>
              <button
                onClick={() => setShowExitPrompt(false)}
                style={{ flex: 1, padding: "0.6rem", background: "transparent", border: "1px solid #cec1a8", borderRadius: "6px", cursor: "pointer", color: "#2a3d30", fontSize: "12px", letterSpacing: "0.08em" }}
              >
                Stay
              </button>
              <button
                onClick={() => { setShowExitPrompt(false); onClose(); }}
                style={{ flex: 1, padding: "0.6rem", background: "#2a3d30", border: "none", borderRadius: "6px", cursor: "pointer", color: "#faf2e8", fontSize: "12px", letterSpacing: "0.08em" }}
              >
                Exit
              </button>
            </div>
          </div>
        </div>
      )}
      {/* Header row with property name and close button */}
      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-start", marginBottom: "1rem" }}>
        <div>
          <p style={{ fontSize: "10px", letterSpacing: "0.12em", textTransform: "uppercase", color: "#b18952", margin: "0 0 4px" }}>
            {property.location}
          </p>
          <h2 style={{ fontSize: "18px", color: "#2a3d30", margin: 0, fontFamily: "'Cormorant Garamond', serif" }}>
            {property.name}
          </h2>
        </div>
        <button
          onClick={tryExit}
          style={{ background: "none", border: "none", fontSize: "22px", color: "#71796e", cursor: "pointer", lineHeight: 1, padding: "0 4px", marginTop: "-4px" }}
          aria-label="Close"
        >
          ×
        </button>
      </div>

      {/* Step indicator — hidden on done/cancelled screens */}
      {step !== "done" && step !== "cancelled" && (
        <div style={{ display: "flex", alignItems: "center", gap: "0.5rem", marginBottom: "1.2rem", flexWrap: "wrap" }}>
          {["dates", "info", "confirm", "paying"].map((s, i) => {
            const stepOrder = ["dates", "info", "confirm", "paying", "done"];
            const current = stepOrder.indexOf(step);
            const idx = stepOrder.indexOf(s);
            const done = current > idx;
            const active = s === step;
            return (
              <span key={s} style={{ display: "flex", alignItems: "center", gap: "0.4rem" }}>
                <span style={{
                  display: "inline-flex", alignItems: "center", justifyContent: "center",
                  width: "20px", height: "20px", borderRadius: "50%",
                  border: `1px solid ${done ? "#71796e" : active ? "#b18952" : "#cec1a8"}`,
                  backgroundColor: done ? "#71796e" : "transparent",
                  color: done ? "#faf2e8" : active ? "#b18952" : "#cec1a8",
                  fontSize: "9px", fontWeight: "bold", transition: "all 0.2s",
                }}>
                  {done ? "✓" : i + 1}
                </span>
                <span style={{
                  fontSize: "10px", letterSpacing: "0.12em", textTransform: "uppercase",
                  color: active ? "#2a3d30" : "#71796e", opacity: active ? 1 : 0.5, transition: "all 0.2s",
                }}>
                  {s === "dates" ? "Dates" : s === "info" ? "Guest" : s === "confirm" ? "Review" : "Pay"}
                </span>
                {i < 3 && <span style={{ width: "16px", height: "1px", backgroundColor: "#cec1a8" }} />}
              </span>
            );
          })}
        </div>
      )}

      {/* Step 1: Dates */}
      {step === "dates" && (
        <div>
          <h3 style={{ fontSize: "1.2rem", marginBottom: "0.25rem", color: "#2a3d30" }}>
            Choose your nights
          </h3>
          <p style={{ color: "#71796e", fontSize: "13px", marginBottom: "0.75rem" }}>
            ₹{property.price_per_night.toLocaleString("en-IN")} / night · min. {property.min_nights ?? 1} night{(property.min_nights ?? 1) > 1 ? "s" : ""}
          </p>

          {/* Calendar */}
          <Calendar
            range={range}
            setRange={setRange}
            blockedSet={blockedSet}
            minNights={property.min_nights ?? 1}
            property={property}
          />

          {range?.from && range?.to && nights > 0 && (
            <div
              style={{
                padding: "1rem",
                backgroundColor: "rgba(250, 242, 232, 0.6)",
                border: "1px solid #cec1a8",
                borderRadius: "4px",
                marginBottom: "1.5rem",
              }}
            >
              <div style={{ display: "flex", justifyContent: "space-between", fontSize: "14px", marginBottom: "0.5rem" }}>
                <span style={{ color: "#71796e" }}>
                  {formatDate(range.from)} → {formatDate(range.to)}
                </span>
                <span style={{ fontWeight: "bold", color: "#71796e" }}>
                  {nights} night{nights > 1 ? "s" : ""}
                </span>
              </div>
              <div style={{ display: "flex", justifyContent: "space-between", fontSize: "12px", color: "#71796e" }}>
                <span>Total stay</span>
                <span>{formatINR(baseTotal)}</span>
              </div>
              {nights < (property.min_nights ?? 1) && (
                <p style={{ color: "#d97757", fontSize: "12px", marginTop: "0.5rem" }}>
                  Minimum stay is {property.min_nights} nights.
                </p>
              )}
            </div>
          )}

          <div style={{ display: "flex", justifyContent: "flex-end" }}>
            <button
              onClick={() => setStep("info")}
              disabled={!canProceedFromDates}
              style={{
                padding: "0.75rem 1.5rem",
                backgroundColor: canProceedFromDates ? "#71796e" : "#cec1a8",
                color: "#faf2e8",
                border: "none",
                borderRadius: "4px",
                fontSize: "12px",
                letterSpacing: "0.12em",
                textTransform: "uppercase",
                cursor: canProceedFromDates ? "pointer" : "not-allowed",
                transition: "all 0.2s",
              }}
              onMouseEnter={(e) => {
                if (canProceedFromDates) e.target.style.backgroundColor = "#5a6b5e";
              }}
              onMouseLeave={(e) => {
                if (canProceedFromDates) e.target.style.backgroundColor = "#71796e";
              }}
            >
              Next — Guest details →
            </button>
          </div>
        </div>
      )}

      {/* Step 2: Guest Info */}
      {step === "info" && (
        <div>
          <h3 style={{ fontSize: "1.5rem", marginBottom: "0.5rem", color: "#2a3d30" }}>
            Guest details
          </h3>
          <p style={{ color: "#71796e", fontSize: "14px", marginBottom: "1.5rem" }}>
            {range?.from && range?.to && `${formatDate(range.from)} – ${formatDate(range.to)} · ${nights} night${nights > 1 ? "s" : ""}`}
          </p>

          <div style={{ marginBottom: "1rem" }}>
            <label style={{ display: "block", fontSize: "10px", letterSpacing: "0.2em", textTransform: "uppercase", marginBottom: "0.5rem", color: "#71796e" }}>
              Full name *
            </label>
            <input
              type="text"
              value={guest.name}
              onChange={(e) => setGuest({ ...guest, name: e.target.value })}
              placeholder="Your name"
              style={{
                width: "100%",
                padding: "0.75rem",
                border: "1px solid #cec1a8",
                borderRadius: "4px",
                fontSize: "14px",
                fontFamily: '"JetBrains Mono", monospace',
                backgroundColor: "#faf2e8",
                boxSizing: "border-box",
              }}
            />
          </div>

          <div style={{ marginBottom: "1rem" }}>
            <label style={{ display: "block", fontSize: "10px", letterSpacing: "0.2em", textTransform: "uppercase", marginBottom: "0.5rem", color: "#71796e" }}>
              Phone
            </label>
            <input
              type="tel"
              value={guest.phone}
              onChange={(e) => setGuest({ ...guest, phone: e.target.value })}
              placeholder="+91 98765 43210"
              style={{
                width: "100%",
                padding: "0.75rem",
                border: "1px solid #cec1a8",
                borderRadius: "4px",
                fontSize: "14px",
                fontFamily: '"JetBrains Mono", monospace',
                backgroundColor: "#faf2e8",
                boxSizing: "border-box",
              }}
            />
          </div>

          <div style={{ marginBottom: "1rem" }}>
            <label style={{ display: "block", fontSize: "10px", letterSpacing: "0.2em", textTransform: "uppercase", marginBottom: "0.5rem", color: "#71796e" }}>
              Email
            </label>
            <input
              type="email"
              value={guest.email}
              onChange={(e) => setGuest({ ...guest, email: e.target.value })}
              placeholder="you@example.com"
              style={{
                width: "100%",
                padding: "0.75rem",
                border: "1px solid #cec1a8",
                borderRadius: "4px",
                fontSize: "14px",
                fontFamily: '"JetBrains Mono", monospace',
                backgroundColor: "#faf2e8",
                boxSizing: "border-box",
              }}
            />
          </div>

          <p style={{ fontSize: "10px", color: "#71796e", marginBottom: "1.5rem" }}>
            * Phone or email required for payment link delivery.
          </p>

          <div style={{ display: "flex", justifyContent: "space-between" }}>
            <button
              onClick={() => setStep("dates")}
              style={{
                background: "none",
                border: "none",
                fontSize: "12px",
                color: "#71796e",
                cursor: "pointer",
                textDecoration: "underline",
                transition: "color 0.2s",
              }}
              onMouseEnter={(e) => (e.target.style.color = "#2a3d30")}
              onMouseLeave={(e) => (e.target.style.color = "#71796e")}
            >
              ← Back
            </button>
            <button
              onClick={() => setStep("confirm")}
              disabled={!canProceedFromInfo}
              style={{
                padding: "0.75rem 1.5rem",
                backgroundColor: canProceedFromInfo ? "#71796e" : "#cec1a8",
                color: "#faf2e8",
                border: "none",
                borderRadius: "4px",
                fontSize: "12px",
                letterSpacing: "0.12em",
                textTransform: "uppercase",
                cursor: canProceedFromInfo ? "pointer" : "not-allowed",
                transition: "all 0.2s",
              }}
              onMouseEnter={(e) => {
                if (canProceedFromInfo) e.target.style.backgroundColor = "#5a6b5e";
              }}
              onMouseLeave={(e) => {
                if (canProceedFromInfo) e.target.style.backgroundColor = "#71796e";
              }}
            >
              Review booking →
            </button>
          </div>
        </div>
      )}

      {/* Step 3: Confirm */}
      {step === "confirm" && (
        <div>
          <h3 style={{ fontSize: "1.5rem", marginBottom: "1.5rem", color: "#2a3d30" }}>
            Review your booking
          </h3>

          <div style={{ border: "1px solid #cec1a8", borderRadius: "4px", overflow: "hidden" }}>
            {/* Stay */}
            <div style={{ padding: "1rem", borderBottom: "1px solid #cec1a8", display: "flex", gap: "1rem" }}>
              <div style={{ color: "#71796e", fontSize: "1.2rem" }}>📅</div>
              <div>
                <div style={{ fontSize: "10px", letterSpacing: "0.15em", textTransform: "uppercase", color: "#71796e", marginBottom: "0.5rem" }}>
                  Stay
                </div>
                <div style={{ fontSize: "14px", color: "#2a3d30" }}>
                  {range?.from && formatDate(range.from)} → {range?.to && formatDate(range.to)}
                </div>
                <div style={{ fontSize: "12px", color: "#71796e", marginTop: "0.25rem" }}>
                  {nights} night{nights > 1 ? "s" : ""}
                </div>
              </div>
            </div>

            {/* Guest */}
            <div style={{ padding: "1rem", borderBottom: "1px solid #cec1a8", display: "flex", gap: "1rem" }}>
              <div style={{ color: "#71796e", fontSize: "1.2rem" }}>👤</div>
              <div>
                <div style={{ fontSize: "10px", letterSpacing: "0.15em", textTransform: "uppercase", color: "#71796e", marginBottom: "0.5rem" }}>
                  Guest
                </div>
                <div style={{ fontSize: "14px", color: "#2a3d30" }}>{guest.name}</div>
                {guest.phone && <div style={{ fontSize: "12px", color: "#71796e" }}>{guest.phone}</div>}
                {guest.email && <div style={{ fontSize: "12px", color: "#71796e" }}>{guest.email}</div>}
              </div>
            </div>

            {/* Payment */}
            {property.price_per_night > 0 && (
              <div style={{ padding: "1rem", display: "flex", gap: "1rem" }}>
                <div style={{ color: "#71796e", fontSize: "1.2rem" }}>💳</div>
                <div style={{ flex: 1 }}>
                  <div style={{ fontSize: "10px", letterSpacing: "0.15em", textTransform: "uppercase", color: "#71796e", marginBottom: "0.75rem" }}>
                    Payment
                  </div>
                  <div style={{ display: "flex", justifyContent: "space-between", fontSize: "14px", marginBottom: "0.5rem" }}>
                    <span style={{ color: "#71796e" }}>
                      {nights} × {formatINR(property.price_per_night)}
                    </span>
                    <span style={{ color: "#2a3d30" }}>{formatINR(baseTotal)}</span>
                  </div>
                  <div style={{ display: "flex", justifyContent: "space-between", fontSize: "14px", fontWeight: "bold", color: "#b18952", marginBottom: "0.5rem" }}>
                    <span>Advance now (50%)</span>
                    <span>{formatINR(advanceAmount)}</span>
                  </div>
                  <div style={{ display: "flex", justifyContent: "space-between", fontSize: "12px", color: "#71796e" }}>
                    <span>Balance at check-in</span>
                    <span>{formatINR(baseTotal - advanceAmount)}</span>
                  </div>
                </div>
              </div>
            )}
          </div>

          {error && (
            <div
              style={{
                marginTop: "1rem",
                padding: "0.75rem",
                backgroundColor: "rgba(217, 119, 87, 0.1)",
                border: "1px solid rgba(217, 119, 87, 0.3)",
                borderRadius: "4px",
                fontSize: "12px",
                color: "#d97757",
              }}
            >
              {error}
            </div>
          )}

          <div style={{ display: "flex", justifyContent: "space-between", marginTop: "1.5rem" }}>
            <button
              onClick={() => setStep("info")}
              style={{
                background: "none",
                border: "none",
                fontSize: "12px",
                color: "#71796e",
                cursor: "pointer",
                textDecoration: "underline",
                transition: "color 0.2s",
              }}
              onMouseEnter={(e) => (e.target.style.color = "#2a3d30")}
              onMouseLeave={(e) => (e.target.style.color = "#71796e")}
            >
              ← Back
            </button>
            <button
              onClick={handleBook}
              disabled={loading}
              style={{
                padding: "0.75rem 1.5rem",
                backgroundColor: loading ? "#cec1a8" : "#b18952",
                color: "#faf2e8",
                border: "none",
                borderRadius: "4px",
                fontSize: "12px",
                letterSpacing: "0.12em",
                textTransform: "uppercase",
                cursor: loading ? "not-allowed" : "pointer",
                transition: "all 0.2s",
              }}
              onMouseEnter={(e) => {
                if (!loading) e.target.style.backgroundColor = "#9d744a";
              }}
              onMouseLeave={(e) => {
                if (!loading) e.target.style.backgroundColor = "#b18952";
              }}
            >
              {loading ? "Processing…" : "Confirm & Pay →"}
            </button>
          </div>
        </div>
      )}

      {/* Step 4: Paying — verify payment via access code */}
      {step === "paying" && result && (
        <div>
          <h3 style={{ fontSize: "1.4rem", marginBottom: "0.5rem", color: "#2a3d30" }}>Complete your payment</h3>
          <p style={{ color: "#71796e", fontSize: "13px", marginBottom: "1.5rem", lineHeight: "1.6" }}>
            Your payment page has opened in a new tab. Once payment is done, the confirmation screen will show a <strong>6-digit access code</strong>. Enter it below to confirm your booking.
          </p>

          <div style={{ marginBottom: "1rem" }}>
            <label style={{ display: "block", fontSize: "10px", letterSpacing: "0.2em", textTransform: "uppercase", marginBottom: "0.5rem", color: "#71796e" }}>
              Access code
            </label>
            <input
              type="text"
              maxLength={6}
              value={codeInput}
              onChange={(e) => { setCodeInput(e.target.value.replace(/\D/g, "")); setCodeError(null); }}
              placeholder="e.g. 482910"
              style={{
                width: "100%", padding: "0.75rem", border: `1px solid ${codeError ? "#d97757" : "#cec1a8"}`,
                borderRadius: "4px", fontSize: "18px", fontFamily: '"JetBrains Mono", monospace',
                backgroundColor: "#faf2e8", letterSpacing: "0.3em", textAlign: "center", boxSizing: "border-box",
              }}
            />
            {codeError && <p style={{ color: "#d97757", fontSize: "12px", marginTop: "0.4rem" }}>{codeError}</p>}
          </div>

          <button
            onClick={async () => {
              setConfirmLoading(true);
              setCodeError(null);
              try {
                await window.confirmBooking(result.booking_id, codeInput);
                setStep("done");
              } catch (e) {
                setCodeError(e.message ?? "Something went wrong. Please try again.");
              } finally {
                setConfirmLoading(false);
              }
            }}
            disabled={codeInput.length < 6 || confirmLoading}
            style={{
              width: "100%", padding: "0.75rem", marginBottom: "1.5rem",
              backgroundColor: (codeInput.length === 6 && !confirmLoading) ? "#2a3d30" : "#cec1a8",
              color: "#faf2e8", border: "none", borderRadius: "4px",
              fontSize: "12px", letterSpacing: "0.12em", textTransform: "uppercase",
              cursor: (codeInput.length === 6 && !confirmLoading) ? "pointer" : "not-allowed", transition: "all 0.2s",
            }}
          >
            {confirmLoading ? "Confirming…" : "Verify & Confirm Booking"}
          </button>

          <div style={{ borderTop: "1px dashed #cec1a8", paddingTop: "1rem", display: "flex", flexDirection: "column", gap: "0.75rem", alignItems: "center" }}>
            <button
              onClick={async () => {
                if (result) await window.cancelBooking(result.booking_id, result.access_code);
                setStep("cancelled");
              }}
              style={{ background: "none", border: "none", fontSize: "13px", color: "#71796e", cursor: "pointer", textDecoration: "underline" }}
            >
              I cancelled my payment
            </button>
            <button
              onClick={() => { onClose(); setTimeout(openContactModal, 100); }}
              style={{ background: "none", border: "none", fontSize: "13px", color: "#b18952", cursor: "pointer", textDecoration: "underline" }}
            >
              Need help? Contact us
            </button>
          </div>
        </div>
      )}

      {/* Step 5: Done — payment verified */}
      {step === "done" && result && (
        <div style={{ textAlign: "center", padding: "1.5rem 0" }}>
          <div style={{ fontSize: "2.5rem", marginBottom: "1rem" }}>✓</div>
          <h3 style={{ fontSize: "1.5rem", marginBottom: "0.5rem", color: "#2a3d30" }}>Booking confirmed</h3>
          <p style={{ color: "#71796e", fontSize: "14px", marginBottom: "1.5rem" }}>
            Your stay at <strong>{result.property_name}</strong> is locked in. See you soon.
          </p>
          <div style={{ border: "1px solid #cec1a8", borderRadius: "4px", padding: "1rem", marginBottom: "1.5rem", textAlign: "left", fontSize: "14px", backgroundColor: "#faf2e8" }}>
            <div style={{ display: "flex", justifyContent: "space-between", marginBottom: "0.5rem" }}>
              <span style={{ color: "#71796e" }}>Booking ref</span>
              <span style={{ fontWeight: "bold", letterSpacing: "0.15em", fontSize: "12px" }}>{result.booking_id.slice(0, 8).toUpperCase()}</span>
            </div>
            <div style={{ display: "flex", justifyContent: "space-between", marginBottom: "0.5rem" }}>
              <span style={{ color: "#71796e" }}>Access code</span>
              <span style={{ fontWeight: "bold", letterSpacing: "0.25em" }}>{result.access_code}</span>
            </div>
            <div style={{ display: "flex", justifyContent: "space-between", color: "#71796e" }}>
              <span>Advance paid</span>
              <span style={{ fontWeight: "bold", color: "#2a3d30" }}>{formatINR(result.amount)}</span>
            </div>
          </div>
          <p style={{ fontSize: "11px", color: "#71796e", marginBottom: "1rem" }}>Keep your access code — you'll need it to check in.</p>
          <button onClick={onClose} style={{ background: "none", border: "none", fontSize: "12px", color: "#71796e", cursor: "pointer", textDecoration: "underline" }}>
            Close
          </button>
        </div>
      )}

      {/* Cancelled state */}
      {step === "cancelled" && (
        <div style={{ textAlign: "center", padding: "1.5rem 0" }}>
          <div style={{ fontSize: "2.5rem", marginBottom: "1rem" }}>✕</div>
          <h3 style={{ fontSize: "1.4rem", marginBottom: "0.5rem", color: "#2a3d30" }}>Payment not completed</h3>
          <p style={{ color: "#71796e", fontSize: "14px", marginBottom: "1.5rem", lineHeight: "1.6" }}>
            No worries — your booking has not been confirmed and those dates are still open. Feel free to try again or contact us if you need help.
          </p>
          <div style={{ display: "flex", flexDirection: "column", gap: "0.75rem" }}>
            <button
              onClick={() => { setStep("dates"); setRange(null); setResult(null); setCodeInput(""); setCodeError(null); }}
              style={{ padding: "0.75rem", backgroundColor: "#2a3d30", color: "#faf2e8", border: "none", borderRadius: "4px", fontSize: "12px", letterSpacing: "0.12em", textTransform: "uppercase", cursor: "pointer" }}
            >
              Try again
            </button>
            <button
              onClick={() => { onClose(); setTimeout(openContactModal, 100); }}
              style={{ padding: "0.75rem", backgroundColor: "transparent", color: "#b18952", border: "1px solid #b18952", borderRadius: "4px", fontSize: "12px", letterSpacing: "0.12em", textTransform: "uppercase", cursor: "pointer" }}
            >
              Contact us
            </button>
            <button onClick={onClose} style={{ background: "none", border: "none", fontSize: "12px", color: "#71796e", cursor: "pointer", textDecoration: "underline", marginTop: "0.25rem" }}>
              Close
            </button>
          </div>
        </div>
      )}
    </div>
  );
}

// Export globally
Object.assign(window, { BookingFlow });
