/* Yogavibe, Reservation & booking page.
   Stripe payment links and Formspree form ID come from config.js
   (window.YOGAVIBE_CONFIG). Manage them centrally there. */
const STRIPE_LINKS = window.YOGAVIBE_CONFIG.stripe.payments;
const FORMSPREE_URL = `https://formspree.io/f/${window.YOGAVIBE_CONFIG.integrations.formspreeFormId}`;

function ReservationPage({ booking, setPage }) {
  const [room, setRoom] = React.useState('twin');
  const [form, setForm] = React.useState({ name: '', email: '', phone: '', dietary: '', notes: '' });
  const [formStatus, setFormStatus] = React.useState('idle'); // idle | loading | success | error

  if (!booking) {
    return (
      <section className="section" style={{ paddingTop: 160 }}>
        <div className="container">
          <p className="caption">No booking selected.</p>
          <button className="btn btn-ghost" onClick={() => setPage('home')} style={{ marginTop: 24 }}>← Back to home</button>
        </div>
      </section>
    );
  }

  const isRetreat = booking.type === 'retreat';
  const priceNum = isRetreat ? (room === 'private' ? 1350 : 1050) : (booking.priceNum || 0);
  const depositAmount = isRetreat ? 500 : priceNum;
  const remainingAmount = isRetreat ? priceNum - 500 : 0;
  const stripeLink = booking.stripeKey ? (STRIPE_LINKS[booking.stripeKey] || null) : null;

  const postToFormspree = (subject) => fetch(FORMSPREE_URL, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json', 'Accept': 'application/json' },
    body: JSON.stringify({
      _subject: subject,
      'Booking': booking.title,
      'Dates': dateDisplay,
      'Name': form.name || '—',
      'Email': form.email || '—',
      'Phone': form.phone || '—',
      ...(isRetreat ? { 'Room': room === 'private' ? 'Single (€1,350)' : 'Twin (€1,050)', 'Dietary': form.dietary || '—' } : {}),
      'Notes': form.notes || '—',
    }),
  }).catch(() => {});

  const handlePay = () => {
    postToFormspree(`Booking intent: ${booking.title} — ${form.name}`);
    let url = stripeLink;
    if (form.email) url += (url.includes('?') ? '&' : '?') + 'prefilled_email=' + encodeURIComponent(form.email);
    window.open(url, '_blank');
  };

  const handleEmailReserve = async () => {
    setFormStatus('loading');
    try {
      await postToFormspree(`Reservation request: ${booking.title} — ${form.name}`);
      setFormStatus('success');
    } catch {
      setFormStatus('error');
    }
  };

  const dateDisplay = booking.dates || [booking.day, booking.date, booking.year].filter(Boolean).join(' ');

  return (
    <>
      <section className="section" style={{ paddingTop: 140 }}>
        <div className="container">
          <button className="caption back-link" onClick={() => setPage(isRetreat ? 'home' : 'workshops')}>← Back</button>

          <div className="reservation-grid">

            {/* ── Left: summary card + price breakdown ── */}
            <div className="reservation-left">
              <div className="reservation-event-card">
                {booking.img && (
                  <div className="reservation-event-img">
                    <Placeholder
                      coords={(booking.loc || '').toUpperCase()}
                      label={booking.title}
                      tag="RES"
                      src={booking.img}
                      pos={booking.pos || 'center'}
                      ratio={16 / 9}
                    />
                  </div>
                )}
                <div className="reservation-event-info">
                  <div className="caption">{booking.loc}</div>
                  <h2 className="h2" style={{ marginTop: 10 }}>{booking.title}</h2>
                  <div className="reservation-meta">
                    <div>
                      <div className="caption">Date</div>
                      <div className="body" style={{ color: 'var(--ink)', marginTop: 4, fontSize: 14 }}>{dateDisplay}</div>
                    </div>
                    {booking.time && (
                      <div>
                        <div className="caption">Time</div>
                        <div className="body" style={{ color: 'var(--ink)', marginTop: 4, fontSize: 14 }}>{booking.time}</div>
                      </div>
                    )}
                  </div>
                </div>
              </div>

              {booking.details && (
                <div className="reservation-details-card">
                  {booking.details.intro.map((p, i) => (
                    <p key={i} className="body" style={{ fontSize: 15, marginBottom: 14 }}>{p}</p>
                  ))}
                  {booking.details.sections && (
                    <div className="reservation-for-whom">
                      <div className="caption" style={{ marginBottom: 16 }}>{booking.details.sectionsLabel || 'What to expect:'}</div>
                      {booking.details.sections.map((s, i) => (
                        <div key={i} className="reservation-section-row">
                          <div className="reservation-for-label">{s.title}</div>
                          <div style={{ fontSize: 14, marginTop: 4, marginBottom: 12 }}>{s.body}</div>
                        </div>
                      ))}
                    </div>
                  )}
                  {booking.details.forWhom && (
                    <div className="reservation-for-whom">
                      <div className="caption" style={{ marginBottom: 12 }}>For whom?</div>
                      {booking.details.forWhom.map(([label, text], i) => (
                        <div key={i} className="reservation-for-row">
                          <span className="reservation-for-label">{label}</span>
                          <span>{text}</span>
                        </div>
                      ))}
                    </div>
                  )}
                  {booking.details.closing && (
                    <p className="body" style={{ fontSize: 15, marginTop: 16, paddingTop: 16, borderTop: '1px solid var(--line)', fontStyle: 'italic' }}>{booking.details.closing}</p>
                  )}
                </div>
              )}

              <div className="reservation-price-card">
                {isRetreat && (
                  <div className="reservation-price-row reservation-price-row--room">
                    <span className="caption">Room type</span>
                    <div className="res-room-toggle">
                      <button type="button" className={room === 'twin' ? 'active' : ''} onClick={() => setRoom('twin')}>Twin · €1,050</button>
                      <button type="button" className={room === 'private' ? 'active' : ''} onClick={() => setRoom('private')}>Single · €1,350</button>
                    </div>
                  </div>
                )}
                <div className="reservation-price-row">
                  <span className="caption">{isRetreat ? 'Full retreat price' : 'Workshop price'}</span>
                  <span>€{priceNum.toLocaleString()}</span>
                </div>
                {isRetreat && (
                  <>
                    <div className="reservation-price-row reservation-price-row--accent">
                      <span>Deposit due today</span>
                      <span style={{ fontFamily: 'var(--font-display)', fontSize: 22, color: 'var(--accent)' }}>€500</span>
                    </div>
                    <div className="reservation-price-row reservation-price-row--soft">
                      <span>Balance · due 45 days before</span>
                      <span>€{remainingAmount.toLocaleString()}</span>
                    </div>
                  </>
                )}
                {!isRetreat && (
                  <div className="reservation-price-row reservation-price-row--accent">
                    <span>Total due today</span>
                    <span style={{ fontFamily: 'var(--font-display)', fontSize: 22, color: 'var(--accent)' }}>{booking.price}</span>
                  </div>
                )}
              </div>
            </div>

            {/* ── Right: form ── */}
            <div className="reservation-form-side">
              <div className="eyebrow">Secure your spot</div>
              <h1 className="h1" style={{ marginTop: 16 }}>
                {isRetreat
                  ? <React.Fragment>Reserve your<br /><em>place.</em></React.Fragment>
                  : <React.Fragment>Book your<br /><em>spot.</em></React.Fragment>
                }
              </h1>
              <p className="body" style={{ marginTop: 20, fontSize: 15 }}>
                {isRetreat
                  ? 'Enter your details below. You\'ll pay a fixed €500 deposit today to secure your spot — the remaining balance is due 45 days before departure.'
                  : 'Enter your details and pay in full to confirm your spot. We\'ll send a confirmation email within 24 hours.'}
              </p>

              <form className="reservation-form" onSubmit={e => { e.preventDefault(); stripeLink ? handlePay() : handleEmailReserve(); }}>
                <div className="res-field">
                  <label>Full name</label>
                  <input type="text" required placeholder="Your full name"
                    value={form.name} onChange={e => setForm({ ...form, name: e.target.value })} />
                </div>
                <div className="res-field">
                  <label>Email</label>
                  <input type="email" required placeholder="you@example.com"
                    value={form.email} onChange={e => setForm({ ...form, email: e.target.value })} />
                </div>
                <div className="res-field">
                  <label>Phone <span className="res-optional">(optional)</span></label>
                  <input type="tel" placeholder="+32 499 000 000"
                    value={form.phone} onChange={e => setForm({ ...form, phone: e.target.value })} />
                </div>
                {isRetreat && (
                  <div className="res-field">
                    <label>Dietary requirements <span className="res-optional">(optional)</span></label>
                    <input type="text" placeholder="Vegetarian, gluten-free, dairy-free…"
                      value={form.dietary} onChange={e => setForm({ ...form, dietary: e.target.value })} />
                  </div>
                )}
                <div className="res-field">
                  <label>Notes or questions <span className="res-optional">(optional)</span></label>
                  <textarea rows="3" placeholder="Anything you'd like us to know"
                    value={form.notes} onChange={e => setForm({ ...form, notes: e.target.value })} />
                </div>

                {stripeLink ? (
                  <button type="submit" className="btn btn-primary"
                    style={{ width: '100%', justifyContent: 'center', marginTop: 12 }}>
                    <span className="dot"></span>
                    {isRetreat ? 'Pay €500 deposit via Stripe' : `Pay ${booking.price} via Stripe`} →
                  </button>
                ) : formStatus === 'success' ? (
                  <div className="newsletter-success" style={{ marginTop: 12 }}>
                    <div className="h3">Request sent ✿</div>
                    <div className="body" style={{ marginTop: 8 }}>Charlotte will be in touch within 24 hours.</div>
                  </div>
                ) : (
                  <div style={{ marginTop: 12, display: 'flex', flexDirection: 'column', gap: 12 }}>
                    <button type="submit" className="btn btn-primary" disabled={formStatus === 'loading'}
                      style={{ width: '100%', justifyContent: 'center' }}>
                      <span className="dot"></span> {formStatus === 'loading' ? 'Sending…' : 'Send reservation request →'}
                    </button>
                    {formStatus === 'error' && <div className="caption" style={{ color: 'var(--accent)' }}>Something went wrong — email <a href={`mailto:${window.YOGAVIBE_CONFIG.contact.email}`}>{window.YOGAVIBE_CONFIG.contact.email}</a> directly.</div>}
                  </div>
                )}
              </form>

              <div className="reservation-trust">
                <div className="stripe-badge">
                  <span className="stripe-logo">stripe</span>
                  <span>Secured by Stripe · SSL encrypted</span>
                </div>
                <div className="caption" style={{ marginTop: 8 }}>
                  {isRetreat ? '€500 deposit is non-refundable · balance due 45 days before departure' : 'Workshop fee is non-refundable'}
                </div>
                <div className="caption" style={{ marginTop: 4 }}>
                  Questions? <a href={`mailto:${window.YOGAVIBE_CONFIG.contact.email}`} style={{ color: 'var(--ink)' }}>{window.YOGAVIBE_CONFIG.contact.email}</a>
                </div>
              </div>
            </div>

          </div>
        </div>
      </section>
    </>
  );
}

Object.assign(window, { ReservationPage });
