/* ============================================================
   BOOKING FLOW — multi-step reservation modal (simulated)
   Opens via window.__gcBook(tierIndex?) ; mounted once in App.
   ============================================================ */
const { useState: bkS, useEffect: bkE } = React;

const BK_T = {
  es: {
    steps: ["Experiencia", "Fecha y hora", "Personas", "Tus datos", "Confirmar"],
    title: "Reservá tu visita",
    next: "Continuar", back: "Atrás", close: "Cerrar",
    chooseExp: "Elegí tu experiencia",
    tiers: [
      { flag:"La Clásica", name:"Visita guiada", dur:"2 horas", price:100, desc:"Visita privada con Sergio + foto en el Batimóvil." },
      { flag:"Experiencia completa", name:"Visita y cena con Sergio", dur:"3 horas", price:200, desc:"Todo lo anterior + cena gourmet íntima con Sergio." },
    ],
    perPerson:"por persona",
    chooseDate:"Elegí la fecha", chooseTime:"Horario disponible",
    noSlots:"Elegí primero un día disponible.",
    months:["Enero","Febrero","Marzo","Abril","Mayo","Junio","Julio","Agosto","Septiembre","Octubre","Noviembre","Diciembre"],
    days:["D","L","M","M","J","V","S"],
    guestsTitle:"¿Cuántas personas?", guestsNote:"No se admiten menores de 12 años.",
    guestsUnit:"personas",
    detailsTitle:"Tus datos de contacto",
    f:{ name:"Nombre y apellido", email:"Email", phone:"WhatsApp", msg:"Comentario (opcional)" },
    review:"Revisá tu reserva",
    rExp:"Experiencia", rDate:"Fecha", rTime:"Horario", rGuests:"Personas", rTotal:"Total", rDeposit:"Seña a pagar ahora (30%)", rRest:"Resto el día de la visita",
    pay:"Confirmar y pagar seña", paying:"Procesando...",
    meetNote:"Te enviaremos la confirmación y el punto de encuentro por WhatsApp y email.",
    confTitle:"¡Reserva confirmada!", confRef:"Código de reserva",
    confBody:"Te esperamos. Vas a recibir todos los detalles por WhatsApp y email.",
    confMeetT:"Punto de encuentro",
    confMeet:"Bell Tower · Weston Town Center<br>1900 Bell Tower Ln, Weston, FL 33326",
    confMeetNote:"Las visitas comienzan acá, no en un domicilio particular.",
    waConfirm:"Confirmar por WhatsApp", done:"Listo",
    req:"Completá este campo.",
    miniReview:{ q:"Una experiencia absolutamente increíble. Su pasión y conocimiento la hicieron inolvidable.", who:"Reseña 5.0 en Tripadvisor" },
  },
  en: {
    steps: ["Experience", "Date & time", "Guests", "Your details", "Confirm"],
    title: "Book your visit",
    next: "Continue", back: "Back", close: "Close",
    chooseExp: "Choose your experience",
    tiers: [
      { flag:"The Classic", name:"Guided Tour", dur:"2 hours", price:100, desc:"Private tour with Sergio + photo in the Batmobile." },
      { flag:"Full experience", name:"Tour & dinner with Sergio", dur:"3 hours", price:200, desc:"Everything above + an intimate gourmet dinner with Sergio." },
    ],
    perPerson:"per person",
    chooseDate:"Choose a date", chooseTime:"Available time",
    noSlots:"Pick an available day first.",
    months:["January","February","March","April","May","June","July","August","September","October","November","December"],
    days:["S","M","T","W","T","F","S"],
    guestsTitle:"How many guests?", guestsNote:"No guests under 12 years old.",
    guestsUnit:"guests",
    detailsTitle:"Your contact details",
    f:{ name:"Full name", email:"Email", phone:"WhatsApp", msg:"Comment (optional)" },
    review:"Review your booking",
    rExp:"Experience", rDate:"Date", rTime:"Time", rGuests:"Guests", rTotal:"Total", rDeposit:"Deposit due now (30%)", rRest:"Balance on the day of your visit",
    pay:"Confirm & pay deposit", paying:"Processing...",
    meetNote:"We'll send your confirmation and the meeting point by WhatsApp and email.",
    confTitle:"Booking confirmed!", confRef:"Booking reference",
    confBody:"We can't wait to host you. You'll receive all the details by WhatsApp and email.",
    confMeetT:"Meeting point",
    confMeet:"Bell Tower · Weston Town Center<br>1900 Bell Tower Ln, Weston, FL 33326",
    confMeetNote:"Tours begin here, not at a residential address.",
    waConfirm:"Confirm on WhatsApp", done:"Done",
    req:"Please complete this field.",
    miniReview:{ q:"As a huge car enthusiast, this was truly a dream come true. The tour exceeded every expectation.", who:"5.0 review on Tripadvisor" },
  },
};

function Booking({ lang, initialTier, onClose }) {
  const t = BK_T[lang] || BK_T.es;
  const [step, setStep] = bkS(1);
  const [tier, setTier] = bkS(initialTier != null ? initialTier : null);
  const [month, setMonth] = bkS(() => { const d = new Date(); return new Date(d.getFullYear(), d.getMonth(), 1); });
  const [date, setDate] = bkS(null);
  const [time, setTime] = bkS(null);
  const [guests, setGuests] = bkS(2);
  const [form, setForm] = bkS({ name:"", email:"", phone:"", msg:"" });
  const [gift, setGift] = bkS(false);
  const g = (window.GC.gift && (window.GC.gift[lang] || window.GC.gift.es)) || { toggle:"", note:"", badge:"" };
  const [touched, setTouched] = bkS(false);
  const [paying, setPaying] = bkS(false);
  const [ref] = bkS(() => "GCM-" + Math.floor(10000 + Math.random() * 89999));

  const modalRef = React.useRef(null);

  bkE(() => {
    document.body.style.overflow = "hidden";
    if (modalRef.current) modalRef.current.focus();
    const onKey = (e) => { if (e.key === "Escape") onClose(); };
    window.addEventListener("keydown", onKey);
    return () => { document.body.style.overflow = ""; window.removeEventListener("keydown", onKey); };
  }, []);

  const slots = tier === 1 ? ["18:30"] : ["11:00", "14:00", "16:30"];
  const today = new Date(); today.setHours(0,0,0,0);

  // availability: future days, museum closed Mon (1) & Tue (2)
  const dayAvailable = (d) => { const x = new Date(d); x.setHours(0,0,0,0); const wd = x.getDay(); return x > today && wd !== 1 && wd !== 2; };

  const total = tier != null ? t.tiers[tier].price * guests : 0;
  const deposit = Math.round(total * 0.3);

  const fmtDate = (d) => d ? `${d.getDate()} ${t.months[d.getMonth()].toLowerCase()} ${d.getFullYear()}` : "";

  const canNext = () => {
    if (step === 1) return tier != null;
    if (step === 2) return date && time;
    if (step === 3) return guests >= 1;
    if (step === 4) return form.name.trim() && /\S+@\S+\.\S+/.test(form.email) && form.phone.trim();
    return true;
  };
  const go = (n) => { setTouched(false); setStep(n); };
  const next = () => { if (!canNext()) { setTouched(true); return; } go(step + 1); };

  const pay = () => { setPaying(true); setTimeout(() => { setPaying(false); go(6); }, 1100); };

  // build calendar grid
  const grid = [];
  const first = new Date(month.getFullYear(), month.getMonth(), 1);
  const startPad = first.getDay();
  const daysInMonth = new Date(month.getFullYear(), month.getMonth() + 1, 0).getDate();
  for (let i = 0; i < startPad; i++) grid.push(null);
  for (let d = 1; d <= daysInMonth; d++) grid.push(new Date(month.getFullYear(), month.getMonth(), d));
  const sameDay = (a, b) => a && b && a.toDateString() === b.toDateString();
  const minMonth = new Date(today.getFullYear(), today.getMonth(), 1);

  const waText = encodeURIComponent(
    (lang === "es" ? "Hola! Quiero confirmar mi reserva " : "Hi! I'd like to confirm my booking ") + ref +
    ": " + (tier != null ? t.tiers[tier].name : "") + ", " + fmtDate(date) + " " + (time || "") + ", " + guests + " " + t.guestsUnit + "."
  );

  return (
    <div className="bk-overlay" onClick={(e) => { if (e.target === e.currentTarget) onClose(); }}>
      <div className="bk-modal" role="dialog" aria-modal="true" aria-label={t.title} ref={modalRef} tabIndex={-1} style={{ outline: "none" }}>
        <button className="bk-close" onClick={onClose} aria-label={t.close}>✕</button>

        {step <= 5 && (
          <div className="bk-head">
            <div className="bk-head-title">{t.title}</div>
            <div className="bk-steps">
              {t.steps.map((s, i) => (
                <div key={i} className={"bk-step" + (step === i + 1 ? " on" : "") + (step > i + 1 ? " done" : "")}>
                  <span className="bk-step-dot">{step > i + 1 ? "✓" : i + 1}</span>
                  <span className="bk-step-lbl">{s}</span>
                </div>
              ))}
            </div>
          </div>
        )}

        <div className="bk-body">
          {/* STEP 1 — experience */}
          {step === 1 && (
            <div className="bk-pane">
              <h3 className="bk-h">{t.chooseExp}</h3>
              <div className="bk-exps">
                {t.tiers.map((x, i) => (
                  <button key={i} className={"bk-exp" + (tier === i ? " sel" : "")} onClick={() => setTier(i)}>
                    <span className="bk-exp-flag">{x.flag}</span>
                    <span className="bk-exp-name">{x.name}</span>
                    <span className="bk-exp-dur">{x.dur}</span>
                    <span className="bk-exp-desc">{x.desc}</span>
                    <span className="bk-exp-price">${x.price} <small>{t.perPerson}</small></span>
                    <span className="bk-radio" aria-hidden="true"></span>
                  </button>
                ))}
              </div>
            </div>
          )}

          {/* STEP 2 — date & time */}
          {step === 2 && (
            <div className="bk-pane">
              <h3 className="bk-h">{t.chooseDate}</h3>
              <div className="bk-cal">
                <div className="bk-cal-head">
                  <button className="bk-cal-nav" disabled={month <= minMonth} onClick={() => setMonth(new Date(month.getFullYear(), month.getMonth() - 1, 1))}>‹</button>
                  <span>{t.months[month.getMonth()]} {month.getFullYear()}</span>
                  <button className="bk-cal-nav" onClick={() => setMonth(new Date(month.getFullYear(), month.getMonth() + 1, 1))}>›</button>
                </div>
                <div className="bk-cal-dow">{t.days.map((d, i) => <span key={i}>{d}</span>)}</div>
                <div className="bk-cal-grid">
                  {grid.map((d, i) => d ? (
                    <button key={i} disabled={!dayAvailable(d)}
                      className={"bk-day" + (sameDay(d, date) ? " sel" : "") + (dayAvailable(d) ? "" : " off")}
                      onClick={() => { setDate(d); setTime(null); }}>{d.getDate()}</button>
                  ) : <span key={i}></span>)}
                </div>
              </div>
              <h3 className="bk-h" style={{ marginTop: 22 }}>{t.chooseTime}</h3>
              {date ? (
                <div className="bk-slots">
                  {slots.map((s) => (
                    <button key={s} className={"bk-slot" + (time === s ? " sel" : "")} onClick={() => setTime(s)}>{s}</button>
                  ))}
                </div>
              ) : <p className="bk-muted">{t.noSlots}</p>}
            </div>
          )}

          {/* STEP 3 — guests */}
          {step === 3 && (
            <div className="bk-pane">
              <h3 className="bk-h">{t.guestsTitle}</h3>
              <div className="bk-stepper">
                <button onClick={() => setGuests(Math.max(1, guests - 1))} disabled={guests <= 1}>−</button>
                <span className="bk-stepper-n">{guests}<small>{t.guestsUnit}</small></span>
                <button onClick={() => setGuests(Math.min(10, guests + 1))} disabled={guests >= 10}>+</button>
              </div>
              <p className="bk-note">{t.guestsNote}</p>
              <div className="bk-runtotal">
                <span>{guests} × ${t.tiers[tier].price}</span>
                <strong>${total}</strong>
              </div>
            </div>
          )}

          {/* STEP 4 — details */}
          {step === 4 && (
            <div className="bk-pane">
              <h3 className="bk-h">{t.detailsTitle}</h3>
              <div className="bk-field">
                <label>{t.f.name}</label>
                <input value={form.name} onChange={(e) => setForm({ ...form, name: e.target.value })} />
                {touched && !form.name.trim() && <span className="bk-err">{t.req}</span>}
              </div>
              <div className="bk-field">
                <label>{t.f.email}</label>
                <input type="email" value={form.email} onChange={(e) => setForm({ ...form, email: e.target.value })} />
                {touched && !/\S+@\S+\.\S+/.test(form.email) && <span className="bk-err">{t.req}</span>}
              </div>
              <div className="bk-field">
                <label>{t.f.phone}</label>
                <input type="tel" placeholder="+1 ..." value={form.phone} onChange={(e) => setForm({ ...form, phone: e.target.value })} />
                {touched && !form.phone.trim() && <span className="bk-err">{t.req}</span>}
              </div>
              <div className="bk-field">
                <label>{t.f.msg}</label>
                <textarea rows="2" value={form.msg} onChange={(e) => setForm({ ...form, msg: e.target.value })}></textarea>
              </div>
              <label className="bk-gift">
                <input type="checkbox" checked={gift} onChange={(e) => setGift(e.target.checked)} />
                <span><strong>{g.toggle}</strong>{gift && <em>{g.note}</em>}</span>
              </label>
            </div>
          )}

          {/* STEP 5 — review & pay */}
          {step === 5 && (
            <div className="bk-pane">
              <h3 className="bk-h">{t.review}</h3>
              <div className="bk-summary">
                <div className="bk-srow"><span>{t.rExp}</span><strong>{t.tiers[tier].name}</strong></div>
                <div className="bk-srow"><span>{t.rDate}</span><strong>{fmtDate(date)}</strong></div>
                <div className="bk-srow"><span>{t.rTime}</span><strong>{time}</strong></div>
                <div className="bk-srow"><span>{t.rGuests}</span><strong>{guests}</strong></div>
                <div className="bk-srow bk-srow--total"><span>{t.rTotal}</span><strong>${total}</strong></div>
                <div className="bk-srow bk-srow--dep"><span>{t.rDeposit}</span><strong>${deposit}</strong></div>
                <div className="bk-srow bk-srow--rest"><span>{t.rRest}</span><span>${total - deposit}</span></div>
              </div>
              <p className="bk-note">{t.meetNote}</p>
              {t.miniReview && (
                <div className="bk-minireview">
                  <span className="bk-minireview-stars">★★★★★</span>
                  <p>“{t.miniReview.q}”</p>
                  <span className="bk-minireview-who">{t.miniReview.who}</span>
                </div>
              )}
              <button className="btn btn--gold bk-pay" onClick={pay} disabled={paying}>
                {paying ? t.paying : `${t.pay} · $${deposit}`}
              </button>
            </div>
          )}

          {/* STEP 6 — confirmation */}
          {step === 6 && (
            <div className="bk-pane bk-conf">
              <div className="bk-conf-ico">✓</div>
              <h3 className="bk-conf-title">{t.confTitle}</h3>
              <div className="bk-conf-ref">{t.confRef}: <strong>{ref}</strong>{gift && <span className="bk-gift-badge">{g.badge}</span>}</div>
              <p className="bk-conf-body">{t.confBody}</p>
              <div className="bk-conf-card">
                <div className="bk-srow"><span>{t.rExp}</span><strong>{t.tiers[tier].name}</strong></div>
                <div className="bk-srow"><span>{t.rDate}</span><strong>{fmtDate(date)} · {time}</strong></div>
                <div className="bk-srow"><span>{t.rGuests}</span><strong>{guests}</strong></div>
              </div>
              <div className="bk-conf-meet">
                <span className="bk-conf-meet-t">{t.confMeetT}</span>
                <p dangerouslySetInnerHTML={{ __html: t.confMeet }} />
                <span className="bk-conf-meet-note">{t.confMeetNote}</span>
              </div>
              <div className="bk-conf-actions">
                <a className="btn btn--gold" href={"https://wa.me/19548172196?text=" + waText} target="_blank" rel="noopener">{t.waConfirm}</a>
                <button className="btn btn--outline" onClick={onClose}>{t.done}</button>
              </div>
            </div>
          )}
        </div>

        {step <= 5 && (
          <div className="bk-foot">
            {step > 1 ? <button className="btn btn--ghost bk-backbtn" onClick={() => go(step - 1)}>{t.back}</button> : <span></span>}
            {step < 5 && <button className={"btn btn--gold" + (canNext() ? "" : " bk-dim")} onClick={next}>{t.next}</button>}
          </div>
        )}
      </div>
    </div>
  );
}

window.Booking = Booking;
