/* reservation.jsx — request form w/ inline validation, confirmation, WhatsApp handoff
   + fixed floating WhatsApp / call buttons */
const { useState: useStateRv, useEffect: useEffectRv } = React;

function Reservation({ prefillRoom, onSubmitted }) {
  const riad = window.RIAD.riad;
  const rooms = window.RIAD.rooms;
  const blank = { name: "", contact: "", room: "", checkin: "", checkout: "", guests: "2", message: "" };
  const [f, setF] = useStateRv(blank);
  const [err, setErr] = useStateRv({});
  const [done, setDone] = useStateRv(null); // holds the submitted booking

  useEffectRv(() => {
    if (prefillRoom) {
      setF((p) => ({ ...p, room: prefillRoom }));
      setDone(null);
    }
  }, [prefillRoom]);

  const set = (k, v) => { setF((p) => ({ ...p, [k]: v })); setErr((e) => ({ ...e, [k]: undefined })); };

  const validate = () => {
    const e = {};
    if (!f.name.trim()) e.name = "Please tell us your name.";
    if (!f.contact.trim()) e.contact = "An email or phone so we can reply.";
    if (!f.checkin) e.checkin = "Choose an arrival date.";
    if (!f.checkout) e.checkout = "Choose a departure date.";
    if (f.checkin && f.checkout && f.checkout <= f.checkin) e.checkout = "Departure must be after arrival.";
    setErr(e);
    return Object.keys(e).length === 0;
  };

  const waText = (b) =>
    encodeURIComponent(
      "Hello " + riad.name + ", I'd like to request a stay:\n" +
      "• Name: " + b.guest + "\n" +
      "• Room: " + b.room + "\n" +
      "• Dates: " + b.checkin + " → " + b.checkout + "\n" +
      "• Guests: " + b.guests + "\n" +
      (b.note ? "• Note: " + b.note + "\n" : "") +
      "(ref " + b.ref + ")"
    );

  const submit = (e) => {
    e.preventDefault();
    if (!validate()) return;
    const booking = {
      ref: "DN-" + Math.floor(2090 + Math.random() * 900),
      guest: f.name.trim(),
      room: f.room || "No preference",
      checkin: f.checkin,
      checkout: f.checkout,
      guests: Number(f.guests),
      channel: "Web",
      status: "New",
      note: f.message.trim(),
      contact: f.contact.trim()
    };
    onSubmitted(booking);
    setDone(booking);
    window.scrollToId("reservation");
  };

  return (
    <section className="section" id="reservation" data-screen-label="Reservation">
      <div className="wrap">
        <div className="resv-grid">
          <div className="resv-aside">
            <SectionHead
              eyebrow="Reservations"
              title="Request your stay."
              sub="No payment now. We hold rooms by hand and reply within the day — usually within the hour."
            />
            <div className="contact-line">
              <a href={"https://wa.me/" + riad.contact.whatsappNumber} target="_blank" rel="noreferrer">
                <span className="k">WhatsApp</span><span className="v">{riad.contact.whatsappLabel}</span>
              </a>
              <a href={"tel:" + riad.contact.phoneNumber}>
                <span className="k">Telephone</span><span className="v">{riad.contact.phoneLabel}</span>
              </a>
              <a href={"mailto:" + riad.contact.email}>
                <span className="k">Email</span><span className="v">{riad.contact.email}</span>
              </a>
            </div>
          </div>

          {done ? (
            <Reveal className="resv-confirm">
              <span className="check">&#10003;</span>
              <h3>Thank you, {done.guest.split(" ")[0]}.</h3>
              <p className="sub" style={{ color: "var(--muted)", maxWidth: "48ch" }}>
                Your request is with the front desk under reference <strong style={{ color: "var(--ink)" }}>{done.ref}</strong>.
                We&rsquo;ll confirm by {done.contact.includes("@") ? "email" : "message"} shortly. To reach us right away, send it through to WhatsApp.
              </p>
              <div className="summary">
                <span className="k">Room</span><span className="v">{done.room}</span>
                <span className="k">Arrive</span><span className="v">{done.checkin}</span>
                <span className="k">Depart</span><span className="v">{done.checkout}</span>
                <span className="k">Guests</span><span className="v">{done.guests}</span>
              </div>
              <div className="form-actions" style={{ display: "flex", gap: "14px", flexWrap: "wrap", marginTop: "6px" }}>
                <a className="btn-solid" href={"https://wa.me/" + riad.contact.whatsappNumber + "?text=" + waText(done)} target="_blank" rel="noreferrer">Send to WhatsApp</a>
                <button className="btn-outline" onClick={() => { setF(blank); setDone(null); }}>New request</button>
              </div>
            </Reveal>
          ) : (
            <Reveal>
              <form className="form" onSubmit={submit} noValidate>
                <div className={"field" + (err.name ? " err" : "")}>
                  <label>Your name</label>
                  <input value={f.name} onChange={(e) => set("name", e.target.value)} placeholder="First & last" />
                  <span className="msg">{err.name}</span>
                </div>
                <div className={"field" + (err.contact ? " err" : "")}>
                  <label>Email or phone</label>
                  <input value={f.contact} onChange={(e) => set("contact", e.target.value)} placeholder="you@example.com" />
                  <span className="msg">{err.contact}</span>
                </div>
                <div className="field full">
                  <label>Room</label>
                  <select value={f.room} onChange={(e) => set("room", e.target.value)}>
                    <option value="">No preference — recommend one</option>
                    {rooms.map((r) => <option key={r.id} value={r.name}>{r.name} — from {r.currency}{r.priceFrom}/night</option>)}
                  </select>
                  <span className="msg"></span>
                </div>
                <div className={"field" + (err.checkin ? " err" : "")}>
                  <label>Arrival</label>
                  <input type="date" value={f.checkin} onChange={(e) => set("checkin", e.target.value)} />
                  <span className="msg">{err.checkin}</span>
                </div>
                <div className={"field" + (err.checkout ? " err" : "")}>
                  <label>Departure</label>
                  <input type="date" value={f.checkout} onChange={(e) => set("checkout", e.target.value)} />
                  <span className="msg">{err.checkout}</span>
                </div>
                <div className="field full">
                  <label>Guests</label>
                  <select value={f.guests} onChange={(e) => set("guests", e.target.value)}>
                    {[1, 2, 3, 4, 5, 6].map((n) => <option key={n} value={n}>{n} {n === 1 ? "guest" : "guests"}</option>)}
                  </select>
                  <span className="msg"></span>
                </div>
                <div className="field full">
                  <label>Anything we should know?</label>
                  <textarea value={f.message} onChange={(e) => set("message", e.target.value)} placeholder="Arrival time, dietary notes, a celebration…"></textarea>
                </div>
                <div className="actions">
                  <button type="submit" className="btn-solid">Send request</button>
                  <span className="note">No card needed. This sends a request only — we confirm availability with you directly.</span>
                </div>
              </form>
            </Reveal>
          )}
        </div>
      </div>
    </section>
  );
}

function Floats() {
  const c = window.RIAD.riad.contact;
  return (
    <div className="floats">
      <a className="float-btn wa" href={"https://wa.me/" + c.whatsappNumber} target="_blank" rel="noreferrer" aria-label="WhatsApp">
        <svg viewBox="0 0 24 24" fill="currentColor"><path d="M12.04 2C6.58 2 2.13 6.45 2.13 11.91c0 1.75.46 3.45 1.32 4.95L2 22l5.25-1.38c1.45.79 3.08 1.21 4.79 1.21 5.46 0 9.91-4.45 9.91-9.91C21.95 6.45 17.5 2 12.04 2zm0 18.15c-1.52 0-3.01-.41-4.31-1.18l-.31-.18-3.12.82.83-3.04-.2-.31a8.2 8.2 0 0 1-1.26-4.37c0-4.54 3.7-8.24 8.24-8.24 2.2 0 4.27.86 5.82 2.42a8.18 8.18 0 0 1 2.41 5.83c.01 4.54-3.69 8.24-8.23 8.24zm4.52-6.16c-.25-.12-1.47-.72-1.69-.81-.23-.08-.39-.12-.56.13-.16.25-.64.81-.79.97-.14.17-.29.19-.54.06-.25-.12-1.05-.39-1.99-1.23-.74-.66-1.23-1.47-1.38-1.72-.14-.25-.01-.38.11-.51.11-.11.25-.29.37-.43.13-.15.17-.25.25-.42.08-.17.04-.31-.02-.43-.06-.12-.56-1.34-.76-1.84-.2-.48-.41-.42-.56-.43h-.48c-.17 0-.43.06-.66.31-.22.25-.86.85-.86 2.07 0 1.22.89 2.4 1.01 2.56.12.17 1.75 2.67 4.24 3.74.59.26 1.05.41 1.41.52.59.19 1.13.16 1.56.1.48-.07 1.47-.6 1.68-1.18.21-.58.21-1.07.14-1.18-.06-.11-.22-.17-.47-.29z"/></svg>
      </a>
      <a className="float-btn" href={"tel:" + c.phoneNumber} aria-label="Call">
        <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6"><path d="M22 16.92v3a2 2 0 0 1-2.18 2 19.8 19.8 0 0 1-8.63-3.07 19.5 19.5 0 0 1-6-6 19.8 19.8 0 0 1-3.07-8.67A2 2 0 0 1 4.11 2h3a2 2 0 0 1 2 1.72c.13.96.36 1.9.7 2.81a2 2 0 0 1-.45 2.11L8.09 9.91a16 16 0 0 0 6 6l1.27-1.27a2 2 0 0 1 2.11-.45c.91.34 1.85.57 2.81.7A2 2 0 0 1 22 16.92z"/></svg>
      </a>
    </div>
  );
}

Object.assign(window, { Reservation, Floats });
