/* ============================================================
   BOOK — multi-step appointment flow
   ============================================================ */
const { useState } = React;

function Book({ go, initialService = null, onBackToList }) {
  const [step, setStep] = useState(initialService ? 2 : 1);
  const [service, setService] = useState(initialService);
  const [date, setDate] = useState(null);
  const [time, setTime] = useState(null);
  const [form, setForm] = useState({ name: '', email: '', phone: '', notes: '' });
  const [sending, setSending] = useState(false);
  const [error, setError] = useState('');

  // build next 10 available days
  const days = [];
  const base = new Date(2026, 5, 15);
  for (let i = 0; i < 10; i++) {
    const d = new Date(base); d.setDate(base.getDate() + i);
    days.push(d);
  }
  const dow = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
  const mon = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];

  const canNext = (step === 1 && service) || (step === 2 && date && time) || (step === 3 && form.name && form.email);
  const svc = SERVICES.find(s => s.id === service);

  const STEPS = ['Service', 'Date & time', 'Your details', 'Confirmed'];

  const submitBooking = async () => {
    setSending(true); setError('');
    const dateStr = date ? `${dow[new Date(date).getDay()]} ${new Date(date).getDate()} ${mon[new Date(date).getMonth()]} 2026` : '';
    try {
      const r = await fetch(`${API_BASE}/api/book`, {
        method: 'POST', headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ name: form.name, email: form.email, phone: form.phone, service: svc?.name, date: dateStr, time, notes: form.notes }),
      });
      const d = await r.json().catch(() => ({}));
      if (!r.ok || !d.ok) throw new Error(d.error || 'failed');
      setStep(4);
    } catch (err) {
      setError('Sorry — your request couldn’t be sent. Please call or email us to book.');
    } finally { setSending(false); }
  };

  return (
    <div className="page book-page">
      <PageHeader
        eyebrow="Services"
        title={<>Reserve your <span className="serif-it" style={{ color: 'var(--clay)' }}>ritual</span></>}
        sub="By appointment only · Tue–Sun, 10am–7pm. Choose your experience below."
      />

      <section className="wrap book-wrap">
        {/* Stepper */}
        <div className="book-stepper">
          {STEPS.map((s, i) => (
            <div key={s} className={`book-stepitem ${step === i + 1 ? 'on' : ''} ${step > i + 1 ? 'done' : ''}`}>
              <span className="book-stepnum">{step > i + 1 ? '✓' : i + 1}</span>
              <span className="book-steplabel">{s}</span>
            </div>
          ))}
        </div>

        <div className="book-grid">
          <div className="book-main">
            {/* STEP 1 — service */}
            {step === 1 && (
              <div className="book-pane">
                <h3 className="book-pane-h display">Choose your experience</h3>
                <div className="book-services">
                  {SERVICES.map(s => (
                    <button key={s.id} className={`book-service ${service === s.id ? 'on' : ''}`} onClick={() => setService(s.id)}>
                      <Placeholder tone={s.tone} label="" glyph={false} className="book-service-art" style={{ width: 84, height: 84, borderRadius: 'var(--r-md)', flex: 'none' }} />
                      <div className="book-service-info">
                        <div className="book-service-top">
                          <h4 className="display">{s.name}</h4>
                          <span className="book-service-price display">${s.price}</span>
                        </div>
                        <p>{s.desc}</p>
                        <span className="book-service-dur">{s.duration}</span>
                      </div>
                      <span className="book-radio" />
                    </button>
                  ))}
                </div>
              </div>
            )}

            {/* STEP 2 — date & time */}
            {step === 2 && (
              <div className="book-pane">
                <h3 className="book-pane-h display">Pick a date</h3>
                <div className="book-days">
                  {days.map((d, i) => {
                    const key = d.toISOString();
                    const sel = date === key;
                    return (
                      <button key={key} className={`book-day ${sel ? 'on' : ''} ${i === 0 ? 'soon' : ''}`} onClick={() => setDate(key)}>
                        <span className="book-day-dow">{dow[d.getDay()]}</span>
                        <span className="book-day-num">{d.getDate()}</span>
                        <span className="book-day-mon">{mon[d.getMonth()]}</span>
                      </button>
                    );
                  })}
                </div>
                <h3 className="book-pane-h display" style={{ marginTop: 44 }}>Choose a time</h3>
                <div className="book-times">
                  {SERVICE_TIMES.map(t => (
                    <button key={t} className={`book-time ${time === t ? 'on' : ''}`} onClick={() => setTime(t)} disabled={!date}>
                      {t} <span className="book-time-ap">{parseInt(t) < 9 || t.startsWith('1') && parseInt(t) <= 5 ? 'PM' : 'AM'}</span>
                    </button>
                  ))}
                </div>
                {!date && <p className="book-hint">Select a date to see available times.</p>}
              </div>
            )}

            {/* STEP 3 — details */}
            {step === 3 && (
              <div className="book-pane">
                <h3 className="book-pane-h display">Your details</h3>
                <div className="book-form">
                  <div className="field"><label>Full name *</label>
                    <input value={form.name} onChange={e => setForm({ ...form, name: e.target.value })} placeholder="Your name" /></div>
                  <div className="field"><label>Email *</label>
                    <input type="email" value={form.email} onChange={e => setForm({ ...form, email: e.target.value })} placeholder="you@email.com" /></div>
                  <div className="field"><label>Phone</label>
                    <input value={form.phone} onChange={e => setForm({ ...form, phone: e.target.value })} placeholder="Optional" /></div>
                  <div className="field" style={{ gridColumn: '1 / -1' }}><label>Anything we should know?</label>
                    <textarea rows="3" value={form.notes} onChange={e => setForm({ ...form, notes: e.target.value })} placeholder="First visit, sensitivities, intentions for your session…" /></div>
                </div>
              </div>
            )}

            {/* STEP 4 — confirmation */}
            {step === 4 && (
              <div className="book-pane book-confirm">
                <div className="book-confirm-mark"><LogoMark size={64} /></div>
                <h3 className="display">Request received</h3>
                <p>Thank you, {form.name.split(' ')[0] || 'friend'}. We’ve received your booking request and will be in
                  touch at <strong>{form.email}</strong> to confirm your appointment. We can’t wait to welcome you.</p>
                <div className="book-confirm-card">
                  <Row label="Experience" val={svc?.name} />
                  <Row label="Date" val={date ? `${dow[new Date(date).getDay()]} ${new Date(date).getDate()} ${mon[new Date(date).getMonth()]} 2026` : ''} />
                  <Row label="Time" val={time} />
                  <Row label="Duration" val={svc?.duration} />
                  <Row label="Total" val={`$${svc?.price}`} big />
                </div>
                <div style={{ display: 'flex', gap: 14, marginTop: 30, flexWrap: 'wrap' }}>
                  <button className="btn btn-clay" onClick={() => go('home')}>Back to home <span className="arrow">→</span></button>
                  <button className="btn btn-ghost" onClick={() => go('products')}>Shop the line</button>
                </div>
              </div>
            )}

            {/* Nav buttons */}
            {step < 4 && error && <p className="book-hint" style={{ color: 'var(--clay)' }}>{error}</p>}
            {step < 4 && (
              <div className="book-nav">
                {step > 1
                  ? <button className="btn btn-ghost" onClick={() => setStep(step - 1)}>← Back</button>
                  : (onBackToList
                      ? <button className="btn btn-ghost" onClick={onBackToList}>← All services</button>
                      : <span />)}
                <button className="btn btn-clay" disabled={!canNext || sending} onClick={() => (step === 3 ? submitBooking() : setStep(step + 1))}>
                  {sending ? 'Sending…' : (step === 3 ? 'Confirm booking' : 'Continue')} <span className="arrow">→</span>
                </button>
              </div>
            )}
          </div>

          {/* Summary rail */}
          <aside className="book-summary">
            <span className="eyebrow gold">Your booking</span>
            <div className="book-sum-art">
              <Placeholder tone={svc?.tone || 'cocoa'} label={svc ? '' : 'Select a service'} glyph={!svc} style={{ aspectRatio: '16/10', borderRadius: 'var(--r-md)' }} />
            </div>
            <Row label="Experience" val={svc?.name || '—'} />
            <Row label="Duration" val={svc?.duration || '—'} />
            <Row label="Date" val={date ? `${new Date(date).getDate()} ${mon[new Date(date).getMonth()]}` : '—'} />
            <Row label="Time" val={time || '—'} />
            <div className="book-sum-divider" />
            <Row label="Total" val={svc ? `$${svc.price}` : '—'} big />
            <p className="book-sum-note">No payment today — settle in-spa. Free rescheduling up to 24h before.</p>
          </aside>
        </div>
      </section>
    </div>
  );
}

function Row({ label, val, big }) {
  return (
    <div className={`book-row ${big ? 'big' : ''}`}>
      <span>{label}</span>
      <strong className={big ? 'display' : ''}>{val}</strong>
    </div>
  );
}

/* ============================================================
   SERVICES — catalog of spa rituals, leads into the booking flow
   ============================================================ */
function Services({ go }) {
  const [booking, setBooking] = useState(null); // service id being booked, or null = catalog

  if (booking !== null) {
    return <Book go={go} initialService={booking} onBackToList={() => setBooking(null)} />;
  }
  return <ServicesCatalog go={go} onBook={setBooking} />;
}

function ServicesCatalog({ go, onBook }) {
  useReveal();
  return (
    <div className="page">
      <PageHeader
        eyebrow="Services"
        title={<>Our spa <span className="serif-it" style={{ color: 'var(--clay)' }}>rituals</span></>}
        sub="By appointment only · Tue–Sun, 10am–7pm. Choose your experience below."
      />

      <section className="wrap" style={{ paddingBottom: 120 }}>
        <div className="shop-grid svc-grid">
          {SERVICES.map((s, i) => (
            <div key={s.id} className="shop-card svc-card reveal" style={{ transitionDelay: `${(i % 3) * 80}ms` }}>
              <div className="shop-card-art">
                <Placeholder tone={s.tone} label={s.name} style={{ aspectRatio: '4/3', borderRadius: 'var(--r-md)' }} />
                <span className="shop-cat-badge">{s.duration}</span>
              </div>
              <div className="shop-card-body">
                <div className="shop-card-top">
                  <h3 className="display">{s.name}</h3>
                  <span className="shop-price display">${s.price}</span>
                </div>
                <p>{s.desc}</p>
                <button className="btn btn-clay svc-book" onClick={() => onBook(s.id)}>
                  Book this ritual <span className="arrow">→</span>
                </button>
              </div>
            </div>
          ))}
        </div>
      </section>

      <CTABand go={go}
        eyebrow="Pair it with the line"
        title={<>Carry the glow <span className="serif-it">home</span></>}
        btn="Shop E Glow Beauty" target="products" secondary={['Read our story', 'about']} />
    </div>
  );
}

Object.assign(window, { Book, Row, Services, ServicesCatalog });
