// pages/reservation.jsx — 4-step reservation flow with working state

function ReservationPage() {
  const { t, lang, navigate, currency, route } = useApp();
  const [step, setStep] = useState(0);

  // Default check-in: tomorrow; check-out: 3 days later
  const today = new Date();
  const defaultIn = new Date(today.getTime() + 86400000);
  const defaultOut = new Date(today.getTime() + 86400000 * 4);
  const fmt = (d) => d.toISOString().slice(0, 10);

  const [booking, setBooking] = useState({
    checkIn: fmt(defaultIn),
    checkOut: fmt(defaultOut),
    adults: 2,
    children: 0,
    promo: "",
    roomIdx: route.params && route.params.roomIdx != null ? route.params.roomIdx : null,
    firstName: "",
    lastName: "",
    email: "",
    phone: "",
    country: lang === "pl" ? "Polska" : "Poland",
    notes: "",
    terms: false,
    // Przelewy24 is temporarily disabled (no production credentials yet), so
    // Revolut transfer is the only enabled method. See the payment section below.
    paymentMethod: "revolut_transfer",
    bookingRef: null,
    payment: null,
    paymentStatus: null,
  });
  const update = (patch) => setBooking((b) => ({ ...b, ...patch }));
  const [submitError, setSubmitError] = useState(null);
  const [submitting, setSubmitting] = useState(false);

  // If user navigated in with a roomIdx, jump to step 2
  useEffect(() => {
    if (booking.roomIdx != null) setStep(1);
  }, []); // eslint-disable-line

  // When user returns from Przelewy24 with ?ref=, jump to confirmation and poll status
  useEffect(() => {
    // Ref arrives in the query string (/reservation?ref=...); also accept the
    // legacy hash form for any in-flight links from before path routing.
    const m = (window.location.search + window.location.hash).match(/[?&]ref=([A-Z0-9-]+)/i);
    if (!m) return;
    const ref = m[1];
    update({ bookingRef: ref });
    setStep(3);
    let cancelled = false;
    const poll = async () => {
      for (let i = 0; i < 12 && !cancelled; i++) {
        try {
          const r = await fetch(`${window.API_BASE}/api/reservations/${ref}`);
          if (r.ok) {
            const data = await r.json();
            update({ paymentStatus: data.payment_status });
            if (data.status === "confirmed") return;
          }
        } catch {}
        await new Promise((res) => setTimeout(res, 2500));
      }
    };
    poll();
    return () => { cancelled = true; };
  }, []); // eslint-disable-line

  const nights = useMemo(() => {
    const a = new Date(booking.checkIn);
    const b = new Date(booking.checkOut);
    return Math.max(1, Math.round((b - a) / 86400000));
  }, [booking.checkIn, booking.checkOut]);

  const roomCard = booking.roomIdx != null ? t.rooms.cards[booking.roomIdx] : null;
  const subtotal = roomCard ? roomCard.priceFrom * nights : 0;
  const taxes = Math.round(subtotal * 0.08);
  const total = subtotal + taxes;

  const submitReservation = async () => {
    setSubmitError(null);
    setSubmitting(true);
    try {
      const body = {
        room_id: booking.roomIdx + 1,
        check_in: booking.checkIn,
        check_out: booking.checkOut,
        adults: booking.adults,
        children: booking.children,
        first_name: booking.firstName,
        last_name: booking.lastName,
        email: booking.email,
        phone: booking.phone,
        country: booking.country,
        notes: booking.notes || null,
        promo: booking.promo || null,
        payment_method: booking.paymentMethod,
        terms: booking.terms,
        language: lang,
      };
      const r = await fetch(`${window.API_BASE}/api/reservations`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(body),
      });
      if (!r.ok) {
        const txt = await r.text();
        if (r.status === 409) {
          throw new Error(lang === "pl" ? "Wybrany pokoj nie jest dostepny w tych dniach." : "The selected room is not available for these dates.");
        }
        throw new Error(txt || "request failed");
      }
      const data = await r.json();
      update({ bookingRef: data.booking_ref, payment: data.payment });
      if (data.payment.method === "przelewy24") {
        window.location.href = data.payment.redirect_url;
        return;
      }
      setStep(3);
      window.scrollTo({ top: 0, behavior: "smooth" });
    } catch (err) {
      setSubmitError(lang === "pl"
        ? "Nie udalo sie utworzyc rezerwacji. " + (err.message || "")
        : "Could not create the reservation. " + (err.message || ""));
    } finally {
      setSubmitting(false);
    }
  };

  const goNext = () => {
    track("reservation_step", { step: step + 1, room_idx: booking.roomIdx });
    if (step === 2) {
      submitReservation();
      return;
    }
    setStep((s) => Math.min(3, s + 1));
    window.scrollTo({ top: 0, behavior: "smooth" });
  };
  const goBack = () => {
    setStep((s) => Math.max(0, s - 1));
    window.scrollTo({ top: 0, behavior: "smooth" });
  };

  const canContinue =
    step === 0 ? booking.checkIn && booking.checkOut && nights > 0 :
    step === 1 ? booking.roomIdx != null :
    step === 2 ? booking.firstName && booking.lastName && booking.email && booking.terms :
    true;

  return (
    <div className="page-enter">
      <section className="page-hero" style={{ padding: "140px 0 60px", background: "var(--bg-2)" }}>
        <div className="container">
          <div className="eyebrow" style={{ marginBottom: 16 }}>{t.reservation.title}</div>
          <h1 style={{ fontFamily: "var(--font-display)", fontSize: "clamp(40px, 5vw, 64px)", fontWeight: 400, lineHeight: 1, marginBottom: 40 }}>
            {step < 3
              ? t.reservation["step" + (step + 1)].title
              : t.reservation.step4.title}
          </h1>
          <Stepper steps={t.reservation.steps} active={step} onJump={(i) => i < step && setStep(i)} />
        </div>
      </section>

      <section className="section" style={{ paddingTop: 60 }}>
        <div className="container">
          {step < 3 ? (
            <div style={{ display: "grid", gridTemplateColumns: "1.6fr 1fr", gap: 60, alignItems: "start" }}>
              <div>
                {step === 0 && <StepDates booking={booking} update={update} nights={nights} />}
                {step === 1 && <StepRoom booking={booking} update={update} />}
                {step === 2 && <StepGuest booking={booking} update={update} />}
                {submitError && (
                  <div style={{ marginTop: 24, padding: "12px 16px", background: "#fdecea", color: "#c0392b", fontSize: 13, border: "1px solid #f5c6cb" }}>
                    {submitError}
                  </div>
                )}
                <div style={{ display: "flex", justifyContent: "space-between", marginTop: 48 }}>
                  {step > 0 ? (
                    <button className="btn btn-ghost" onClick={goBack} disabled={submitting}>
                      <Ic.arrowL /> {t.common.back}
                    </button>
                  ) : <span />}
                  <button
                    className="btn"
                    disabled={!canContinue || submitting}
                    style={{ opacity: (!canContinue || submitting) ? 0.5 : 1, cursor: (!canContinue || submitting) ? "not-allowed" : "pointer" }}
                    onClick={goNext}
                  >
                    {submitting ? (lang === "pl" ? "Przetwarzanie..." : "Processing...") : (step === 2 ? t.common.confirm : t.common.next)} <Ic.arrow />
                  </button>
                </div>
              </div>
              <ReservationSummary booking={booking} nights={nights} subtotal={subtotal} taxes={taxes} total={total} roomCard={roomCard} />
            </div>
          ) : (
            <StepConfirmation booking={booking} nights={nights} total={total} roomCard={roomCard} />
          )}
        </div>
      </section>
    </div>
  );
}

// ─── Stepper ───────────────────────────────────────────────────────────────
function Stepper({ steps, active, onJump }) {
  return (
    <div style={{ display: "grid", gridTemplateColumns: `repeat(${steps.length}, 1fr)`, gap: 0, borderTop: "1px solid var(--line-2)" }}>
      {steps.map((s, i) => {
        const done = i < active;
        const isActive = i === active;
        return (
          <button key={i} onClick={() => onJump(i)} style={{
            background: "none", border: 0, padding: "20px 0",
            borderTop: isActive ? "2px solid var(--accent)" : done ? "2px solid var(--accent)" : "2px solid transparent",
            marginTop: -1,
            display: "flex", alignItems: "center", gap: 14,
            cursor: done ? "pointer" : "default",
            textAlign: "left",
            color: isActive || done ? "var(--ink)" : "var(--ink-3)",
          }}>
            <span style={{
              width: 28, height: 28, display: "grid", placeItems: "center",
              border: "1px solid " + (isActive || done ? "var(--accent)" : "var(--line-2)"),
              background: done ? "var(--accent)" : "transparent",
              color: done ? "var(--on-accent)" : (isActive ? "var(--accent)" : "var(--ink-3)"),
              fontFamily: "var(--font-display)",
              fontStyle: "italic",
              fontSize: 14,
            }}>
              {done ? <Ic.check /> : i + 1}
            </span>
            <span className="uppercase">{s}</span>
          </button>
        );
      })}
    </div>
  );
}

// ─── Step 1: Dates ────────────────────────────────────────────────────────
function StepDates({ booking, update, nights }) {
  const { t, lang } = useApp();
  return (
    <div>
      <p className="lead" style={{ marginBottom: 40 }}>{t.reservation.step1.sub}</p>
      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 16, marginBottom: 16 }}>
        <DateField label={t.common.checkIn} value={booking.checkIn} onChange={(v) => update({ checkIn: v })} />
        <DateField label={t.common.checkOut} value={booking.checkOut} onChange={(v) => update({ checkOut: v })} />
      </div>
      <div style={{ padding: "16px 20px", background: "var(--bg-2)", borderLeft: "2px solid var(--accent)", display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 28 }}>
        <span className="uppercase" style={{ color: "var(--ink-2)" }}>{lang === "pl" ? "Długość pobytu" : "Length of stay"}</span>
        <span style={{ fontFamily: "var(--font-display)", fontSize: 24 }}>{nights} {nightsLabel(nights, lang)}</span>
      </div>
      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 16, marginBottom: 28 }}>
        <Stepper2 label={t.common.adults} value={booking.adults} min={1} max={4} onChange={(v) => update({ adults: v })} />
        <Stepper2 label={t.common.children} value={booking.children} min={0} max={3} onChange={(v) => update({ children: v })} />
      </div>
      <div className="field" style={{ maxWidth: 320 }}>
        <label>{t.reservation.step1.promo}</label>
        <input type="text" value={booking.promo} onChange={(e) => update({ promo: e.target.value })} placeholder="DLUGA10" />
      </div>
    </div>
  );
}

function DateField({ label, value, onChange }) {
  return (
    <div className="field">
      <label>{label}</label>
      <div style={{ position: "relative" }}>
        <input type="date" value={value} onChange={(e) => onChange(e.target.value)} style={{ paddingRight: 44 }} />
        <Ic.calendar style={{ position: "absolute", right: 14, top: "50%", transform: "translateY(-50%)", pointerEvents: "none", color: "var(--ink-3)" }} />
      </div>
    </div>
  );
}

function Stepper2({ label, value, min, max, onChange }) {
  return (
    <div className="field">
      <label>{label}</label>
      <div style={{ display: "flex", alignItems: "center", border: "1px solid var(--line)", background: "var(--paper)" }}>
        <button onClick={() => onChange(Math.max(min, value - 1))} style={{ background: "none", border: 0, padding: "14px 18px", fontSize: 18, color: "var(--ink-2)", cursor: "pointer" }}>−</button>
        <span style={{ flex: 1, textAlign: "center", fontFamily: "var(--font-display)", fontSize: 22 }}>{value}</span>
        <button onClick={() => onChange(Math.min(max, value + 1))} style={{ background: "none", border: 0, padding: "14px 18px", fontSize: 18, color: "var(--ink-2)", cursor: "pointer" }}>+</button>
      </div>
    </div>
  );
}

function nightsLabel(n, lang) {
  if (lang === "en") return n === 1 ? "night" : "nights";
  // Polish plural: 1 noc, 2-4 noce, else nocy
  if (n === 1) return "noc";
  const mod10 = n % 10, mod100 = n % 100;
  if (mod10 >= 2 && mod10 <= 4 && (mod100 < 10 || mod100 >= 20)) return "noce";
  return "nocy";
}

// ─── Step 2: Choose room ──────────────────────────────────────────────────
function StepRoom({ booking, update }) {
  const { t, currency } = useApp();
  return (
    <div>
      <p className="lead" style={{ marginBottom: 40 }}>{t.reservation.step2.sub}</p>
      <div style={{ display: "flex", flexDirection: "column", gap: 20 }}>
        {t.rooms.cards.map((c, i) => {
          const selected = booking.roomIdx === i;
          return (
            <button
              key={i}
              onClick={() => update({ roomIdx: i })}
              style={{
                background: "var(--paper)",
                border: "1px solid " + (selected ? "var(--accent)" : "var(--line)"),
                outline: selected ? "1px solid var(--accent)" : "none",
                outlineOffset: -2,
                padding: 0,
                display: "grid",
                gridTemplateColumns: "260px 1fr auto",
                gap: 28,
                textAlign: "left",
                cursor: "pointer",
                transition: "border-color .3s",
              }}
            >
              <Photo src={roomImg(i)} alt={c.name} ratio="auto" style={{ height: "100%", minHeight: 180 }} />
              <div style={{ padding: "24px 0", display: "flex", flexDirection: "column", justifyContent: "center" }}>
                <div className="eyebrow" style={{ marginBottom: 12 }}>{c.tag}</div>
                <h3 className="h3" style={{ marginBottom: 10 }}>{c.name}</h3>
                <p style={{ fontSize: 13, color: "var(--ink-2)", marginBottom: 14 }}>{c.desc}</p>
                <div style={{ display: "flex", gap: 20, flexWrap: "wrap", fontSize: 12, color: "var(--ink-3)" }}>
                  {c.meta.map((m, j) => <span key={j}>{m}</span>)}
                </div>
              </div>
              <div style={{ padding: "24px 28px 24px 0", textAlign: "right", display: "flex", flexDirection: "column", justifyContent: "center", alignItems: "flex-end" }}>
                <div className="uppercase" style={{ color: "var(--ink-3)", marginBottom: 6 }}>{t.common.from}</div>
                <div style={{ fontFamily: "var(--font-display)", fontSize: 36, lineHeight: 1, marginBottom: 6 }}>
                  {formatPrice(c.priceFrom, currency)}
                </div>
                <div style={{ fontSize: 11, color: "var(--ink-2)", marginBottom: 16 }}>{t.common.perNight}</div>
                <span style={{
                  display: "inline-flex", alignItems: "center", gap: 8,
                  padding: "8px 14px",
                  background: selected ? "var(--accent)" : "transparent",
                  color: selected ? "var(--on-accent)" : "var(--ink)",
                  border: "1px solid " + (selected ? "var(--accent)" : "var(--ink)"),
                  fontSize: 10, letterSpacing: "0.18em", textTransform: "uppercase",
                }}>
                  {selected ? <><Ic.check /> {useApp().lang === "pl" ? "Wybrano" : "Selected"}</> : useApp().lang === "pl" ? "Wybierz" : "Select"}
                </span>
              </div>
            </button>
          );
        })}
      </div>
    </div>
  );
}

// ─── Step 3: Guest details ────────────────────────────────────────────────
function StepGuest({ booking, update }) {
  const { t, lang } = useApp();
  return (
    <div>
      <p className="lead" style={{ marginBottom: 40 }}>{t.reservation.step3.sub}</p>
      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 16, marginBottom: 16 }}>
        <div className="field">
          <label>{t.reservation.step3.firstName}</label>
          <input type="text" value={booking.firstName} onChange={(e) => update({ firstName: e.target.value })} />
        </div>
        <div className="field">
          <label>{t.reservation.step3.lastName}</label>
          <input type="text" value={booking.lastName} onChange={(e) => update({ lastName: e.target.value })} />
        </div>
        <div className="field">
          <label>{t.reservation.step3.email}</label>
          <input type="email" value={booking.email} onChange={(e) => update({ email: e.target.value })} />
        </div>
        <div className="field">
          <label>{t.reservation.step3.phone}</label>
          <input type="tel" value={booking.phone} onChange={(e) => update({ phone: e.target.value })} placeholder="+48 ..." />
        </div>
        <div className="field" style={{ gridColumn: "1 / -1" }}>
          <label>{t.reservation.step3.country}</label>
          <input type="text" value={booking.country} onChange={(e) => update({ country: e.target.value })} />
        </div>
        <div className="field" style={{ gridColumn: "1 / -1" }}>
          <label>{t.reservation.step3.notes}</label>
          <textarea rows={4} value={booking.notes} onChange={(e) => update({ notes: e.target.value })} placeholder={t.reservation.step3.notesPh} />
        </div>
      </div>
      <label style={{ display: "flex", alignItems: "flex-start", gap: 12, marginTop: 20, cursor: "pointer" }}>
        <input type="checkbox" checked={booking.terms} onChange={(e) => update({ terms: e.target.checked })} style={{ marginTop: 4, accentColor: "var(--accent)" }} />
        <span style={{ fontSize: 13, color: "var(--ink-2)" }}>{t.reservation.step3.terms}</span>
      </label>

      <div style={{ marginTop: 32, paddingTop: 24, borderTop: "1px solid var(--line)" }}>
        <div className="uppercase" style={{ color: "var(--ink-3)", marginBottom: 14 }}>
          {lang === "pl" ? "Sposob platnosci" : "Payment method"}
        </div>
        <div style={{ display: "grid", gap: 10 }}>
          <PaymentOption
            value="revolut_transfer"
            current={booking.paymentMethod}
            onChange={(v) => update({ paymentMethod: v })}
            title={lang === "pl" ? "Przelew / płatność Revolut" : "Revolut transfer / payment"}
            sub={lang === "pl" ? "Zapłać linkiem Revolut lub przelewem — dane pokażemy po potwierdzeniu (prosimy o wpłatę w ciągu 24h)." : "Pay by Revolut link or transfer — details shown after confirmation (please pay within 24h)."}
          />
          {/* TODO: re-enable Przelewy24 once production credentials are set in
              backend/.env (PRZELEWY24_* + PRZELEWY24_SANDBOX=false). Then remove
              `disabled` here and set the default paymentMethod back if desired. */}
          <PaymentOption
            value="przelewy24"
            current={booking.paymentMethod}
            onChange={(v) => update({ paymentMethod: v })}
            disabled
            title={lang === "pl" ? "Przelewy24 (BLIK, karta, szybki przelew)" : "Przelewy24 (BLIK, card, fast transfer)"}
            sub={lang === "pl" ? "Płatność online — już wkrótce." : "Online payment — coming soon."}
          />
        </div>
      </div>
    </div>
  );
}

function PaymentOption({ value, current, onChange, title, sub, disabled = false }) {
  const selected = current === value;
  return (
    <label style={{
      display: "flex", gap: 14, padding: "14px 16px",
      border: "1px solid " + (selected ? "var(--accent)" : "var(--line)"),
      background: "var(--paper)",
      cursor: disabled ? "not-allowed" : "pointer",
      opacity: disabled ? 0.5 : 1,
    }}>
      <input type="radio" name="paymentMethod" value={value} checked={selected} disabled={disabled} onChange={() => !disabled && onChange(value)} style={{ marginTop: 4, accentColor: "var(--accent)" }} />
      <div>
        <div style={{ fontSize: 14, color: "var(--ink)" }}>{title}</div>
        <div style={{ fontSize: 12, color: "var(--ink-2)", marginTop: 4 }}>{sub}</div>
      </div>
    </label>
  );
}

// ─── Summary panel ────────────────────────────────────────────────────────
function ReservationSummary({ booking, nights, subtotal, taxes, total, roomCard }) {
  const { t, lang, currency } = useApp();
  const niceDate = (d) => {
    const date = new Date(d);
    return date.toLocaleDateString(lang === "pl" ? "pl-PL" : "en-GB", { day: "2-digit", month: "short", year: "numeric" });
  };
  return (
    <aside style={{ background: "var(--paper)", padding: 32, position: "sticky", top: 120, border: "1px solid var(--line)" }}>
      <div className="eyebrow" style={{ marginBottom: 24 }}>{t.common.summary}</div>
      <h3 className="h3" style={{ marginBottom: 24 }}>
        {roomCard ? roomCard.name : (lang === "pl" ? "Wybierz pokój" : "Choose a room")}
      </h3>
      {roomCard && <Photo src={roomImg(booking.roomIdx)} alt={roomCard.name} ratio="16/9" style={{ marginBottom: 24 }} />}

      <Line label={t.common.checkIn} value={niceDate(booking.checkIn)} />
      <Line label={t.common.checkOut} value={niceDate(booking.checkOut)} />
      <Line label={lang === "pl" ? "Długość" : "Length"} value={`${nights} ${nightsLabel(nights, lang)}`} />
      <Line label={t.common.guests} value={`${booking.adults} ${lang === "pl" ? "dorosłych" : "adults"}${booking.children ? `, ${booking.children} ${lang === "pl" ? "dzieci" : "kids"}` : ""}`} />

      <Divider />

      {roomCard ? (
        <>
          <Line label={`${roomCard.name} × ${nights}`} value={formatPrice(subtotal, currency)} />
          <Line label={lang === "pl" ? "Podatki i opłaty" : "Taxes & fees"} value={formatPrice(taxes, currency)} />
          <hr className="rule" style={{ margin: "16px 0" }} />
          <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline", marginBottom: 6 }}>
            <span className="uppercase" style={{ color: "var(--ink)" }}>{t.common.total}</span>
            <span style={{ fontFamily: "var(--font-display)", fontSize: 32, color: "var(--ink)" }}>{formatPrice(total, currency)}</span>
          </div>
          <div style={{ fontSize: 11, color: "var(--ink-3)", textAlign: "right" }}>
            {lang === "pl" ? "VAT i opłata klimatyczna w cenie" : "VAT and local tax included"}
          </div>
        </>
      ) : (
        <p style={{ fontSize: 13, color: "var(--ink-2)" }}>
          {lang === "pl" ? "Przejdź dalej, aby zobaczyć dostępne pokoje." : "Continue to see available rooms."}
        </p>
      )}
    </aside>
  );
}

function Line({ label, value }) {
  return (
    <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline", padding: "10px 0", borderBottom: "1px dashed var(--line)" }}>
      <span className="uppercase" style={{ color: "var(--ink-3)" }}>{label}</span>
      <span style={{ fontSize: 13, color: "var(--ink)" }}>{value}</span>
    </div>
  );
}

// ─── Step 4: Confirmation ─────────────────────────────────────────────────
function StepConfirmation({ booking, nights, total, roomCard }) {
  const { t, lang, navigate, currency } = useApp();
  const niceDate = (d) => new Date(d).toLocaleDateString(lang === "pl" ? "pl-PL" : "en-GB", { day: "2-digit", month: "long", year: "numeric" });
  return (
    <div style={{ maxWidth: 720, margin: "0 auto", textAlign: "center" }}>
      <div style={{ margin: "0 auto 32px", width: 72, height: 72, border: "1px solid var(--accent)", display: "grid", placeItems: "center", color: "var(--accent)" }}>
        <Ic.check style={{ width: 24, height: 24 }} />
      </div>
      <p className="lead" style={{ textAlign: "center", margin: "0 auto 40px" }}>{t.reservation.step4.sub}</p>

      <div style={{ background: "var(--bg-2)", padding: 40, textAlign: "left", marginBottom: 32 }}>
        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline", marginBottom: 32, paddingBottom: 24, borderBottom: "1px solid var(--line-2)" }}>
          <div>
            <div className="uppercase" style={{ color: "var(--ink-3)", marginBottom: 6 }}>{t.reservation.step4.ref}</div>
            <div style={{ fontFamily: "var(--font-display)", fontSize: 32, letterSpacing: "0.04em" }}>{booking.bookingRef}</div>
          </div>
          <div style={{ textAlign: "right" }}>
            <div className="uppercase" style={{ color: "var(--ink-3)", marginBottom: 6 }}>{lang === "pl" ? "Gość" : "Guest"}</div>
            <div style={{ fontSize: 16 }}>{booking.firstName} {booking.lastName}</div>
          </div>
        </div>
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 24 }}>
          <div>
            <div className="uppercase" style={{ color: "var(--ink-3)", marginBottom: 8 }}>{t.common.checkIn}</div>
            <div style={{ fontFamily: "var(--font-display)", fontSize: 22 }}>{niceDate(booking.checkIn)}</div>
            <div className="caption">{lang === "pl" ? "od 15:00" : "from 3:00 pm"}</div>
          </div>
          <div>
            <div className="uppercase" style={{ color: "var(--ink-3)", marginBottom: 8 }}>{t.common.checkOut}</div>
            <div style={{ fontFamily: "var(--font-display)", fontSize: 22 }}>{niceDate(booking.checkOut)}</div>
            <div className="caption">{lang === "pl" ? "do 12:00" : "until 12:00 pm"}</div>
          </div>
          <div>
            <div className="uppercase" style={{ color: "var(--ink-3)", marginBottom: 8 }}>{t.common.room}</div>
            <div style={{ fontFamily: "var(--font-display)", fontSize: 22 }}>{roomCard && roomCard.name}</div>
            <div className="caption">{nights} {nightsLabel(nights, lang)}</div>
          </div>
          <div>
            <div className="uppercase" style={{ color: "var(--ink-3)", marginBottom: 8 }}>{t.common.total}</div>
            <div style={{ fontFamily: "var(--font-display)", fontSize: 22, color: "var(--accent)" }}>{formatPrice(total, currency)}</div>
            <div className="caption">
              {booking.payment && booking.payment.method === "revolut_transfer"
                ? (lang === "pl" ? "przelew na konto Revolut" : "bank transfer to Revolut")
                : booking.paymentStatus === "paid"
                  ? (lang === "pl" ? "oplacono" : "paid")
                  : (lang === "pl" ? "oczekuje na platnosc" : "awaiting payment")}
            </div>
          </div>
        </div>
      </div>

      {booking.payment && booking.payment.method === "revolut_transfer" && (
        <RevolutTransferBox payment={booking.payment} lang={lang} />
      )}

      <p className="muted" style={{ fontSize: 14, marginBottom: 32 }}>
        {lang === "pl"
          ? "Zameldowanie jest samodzielne — instrukcje wyślemy przed przyjazdem. W razie pytań jesteśmy dostępni telefonicznie i na WhatsApp."
          : "Check-in is self-service — we'll send instructions before arrival. For any questions, reach us by phone or WhatsApp."}
      </p>
      <div style={{ display: "flex", gap: 16, justifyContent: "center", flexWrap: "wrap" }}>
        <button className="btn btn-ghost" onClick={() => navigate("home")}>{lang === "pl" ? "Powrót na stronę" : "Back to homepage"}</button>
        <button className="btn" onClick={() => navigate("reservation")}>{t.reservation.step4.newReservation}</button>
      </div>
    </div>
  );
}

function RevolutTransferBox({ payment, lang }) {
  return (
    <div style={{ background: "var(--paper)", border: "1px solid var(--accent)", padding: 28, marginBottom: 32, textAlign: "left" }}>
      <div className="eyebrow" style={{ marginBottom: 16, color: "var(--accent)" }}>
        {lang === "pl" ? "Dane do płatności" : "Payment details"}
      </div>
      <div style={{ display: "grid", gridTemplateColumns: "140px 1fr", gap: "10px 16px", fontSize: 14 }}>
        <div className="uppercase" style={{ color: "var(--ink-3)" }}>{lang === "pl" ? "Odbiorca" : "Recipient"}</div>
        <div>{payment.recipient}</div>
        {payment.iban && (
          <>
            <div className="uppercase" style={{ color: "var(--ink-3)" }}>IBAN</div>
            <div style={{ fontFamily: "monospace" }}>{payment.iban}</div>
          </>
        )}
        <div className="uppercase" style={{ color: "var(--ink-3)" }}>{lang === "pl" ? "Tytuł" : "Title"}</div>
        <div style={{ fontFamily: "monospace" }}>{payment.title}</div>
        <div className="uppercase" style={{ color: "var(--ink-3)" }}>{lang === "pl" ? "Kwota" : "Amount"}</div>
        <div style={{ fontFamily: "var(--font-display)", fontSize: 20 }}>{payment.amount} {payment.currency}</div>
      </div>
      {payment.link && (
        <a
          href={payment.link}
          target="_blank"
          rel="noopener"
          className="btn"
          style={{ display: "inline-flex", alignItems: "center", gap: 10, marginTop: 20 }}
        >
          {lang === "pl" ? "Zapłać przez Revolut" : "Pay with Revolut"} <Ic.arrow />
        </a>
      )}
      <p style={{ fontSize: 12, color: "var(--ink-2)", marginTop: 18, paddingTop: 14, borderTop: "1px dashed var(--line)" }}>
        {payment.instructions}
      </p>
    </div>
  );
}

Object.assign(window, { ReservationPage });
