// components/booking-modal.jsx — multi-step booking modal: tour → date → guests → contact → confirm

function BookingModal({ open, onClose, initialTour }) {
  const [step, setStep] = React.useState(0);
  const [tour, setTour] = React.useState(initialTour || TOURS[0]);
  const [dateIdx, setDateIdx] = React.useState(0);
  const [adults, setAdults] = React.useState(2);
  const [kids, setKids] = React.useState(0);
  const [name, setName] = React.useState('');
  const [email, setEmail] = React.useState('');
  const [phone, setPhone] = React.useState('');
  const [agree, setAgree] = React.useState(false);

  React.useEffect(() => {
    if (initialTour) setTour(initialTour);
    if (open) setStep(0);
  }, [open, initialTour]);

  if (!open) return null;

  const today = new Date();
  const dates = Array.from({ length: 14 }, (_, i) => {
    const d = new Date(today); d.setDate(today.getDate() + i);
    const moon = getMoonPhase(d);
    return { d, moon, best: moonBestFor(moon) };
  });

  const isPrivate = tour.id === 'private';
  const total = isPrivate ? tour.price : (tour.price * adults) + ((tour.childPrice || 0) * kids);

  const steps = ['Tour', 'Date', 'Guests', 'Contact', 'Confirm'];

  const canAdvance = (() => {
    if (step === 1) return dateIdx >= 0;
    if (step === 2) return (adults + kids) > 0;
    if (step === 3) return name && email && phone && agree;
    return true;
  })();

  return (
    <div className="modal-bg" onClick={onClose}>
      <div className="modal" onClick={e => e.stopPropagation()} style={{ maxWidth: 820 }}>
        {/* Header */}
        <div className="modal-hd">
          <div>
            <div className="eyebrow" style={{ marginBottom: 4 }}>Book your night</div>
            <div className="display" style={{ fontSize: 22 }}
                 dangerouslySetInnerHTML={{ __html: tour.name }} />
          </div>
          <button onClick={onClose} aria-label="Close" style={{
            background: 'transparent', border: 0, padding: 8,
          }}><IconClose size={20} /></button>
        </div>

        {/* Stepper */}
        <div style={{ display: 'flex', padding: '14px 28px', gap: 10, borderBottom: '1px solid var(--c-line)',
                      background: 'var(--c-paper-2)' }}>
          {steps.map((s, i) => (
            <div key={s} style={{
              flex: 1, display: 'flex', alignItems: 'center', gap: 8,
              fontFamily: 'var(--f-ui)', fontSize: 12, fontWeight: 600,
              color: i === step ? 'var(--c-ink)' : i < step ? 'var(--c-rock)' : 'var(--c-mute)',
              letterSpacing: '0.04em',
            }}>
              <span style={{
                width: 20, height: 20, borderRadius: '50%',
                background: i < step ? 'var(--c-rock)' : i === step ? 'var(--c-ink)' : 'transparent',
                border: i >= step ? '1px solid var(--c-line)' : 'none',
                color: i < step ? 'white' : i === step ? 'white' : 'var(--c-mute)',
                display: 'inline-flex', alignItems: 'center', justifyContent: 'center', fontSize: 10,
              }}>{i < step ? '✓' : i + 1}</span>
              <span className="step-label">{s}</span>
            </div>
          ))}
        </div>

        {/* Body */}
        <div className="modal-body">
          {step === 0 && <StepTour tour={tour} setTour={setTour} />}
          {step === 1 && <StepDate dates={dates} idx={dateIdx} setIdx={setDateIdx} tour={tour} />}
          {step === 2 && <StepGuests tour={tour} adults={adults} setAdults={setAdults} kids={kids} setKids={setKids} />}
          {step === 3 && <StepContact name={name} setName={setName} email={email} setEmail={setEmail}
                                       phone={phone} setPhone={setPhone} agree={agree} setAgree={setAgree} />}
          {step === 4 && <StepConfirm tour={tour} date={dates[dateIdx]} adults={adults} kids={kids}
                                      name={name} email={email} phone={phone} total={total} />}
        </div>

        {/* Footer */}
        <div className="modal-foot">
          <div>
            {step < 4 ? (
              <div>
                <div style={{ fontFamily: 'var(--f-ui)', fontSize: 11, letterSpacing: '0.12em',
                              textTransform: 'uppercase', color: 'var(--c-mute)' }}>
                  {isPrivate ? 'Flat rate' : 'Estimated'}
                </div>
                <div className="num" style={{ fontSize: 26 }}>
                  ${total.toLocaleString()}
                  {!isPrivate && <span style={{ fontSize: 12, fontFamily: 'var(--f-ui)', color: 'var(--c-mute)', marginLeft: 6 }}>
                    {adults + kids > 0 && `· ${adults + kids} guests`}
                  </span>}
                </div>
              </div>
            ) : (
              <div style={{ fontFamily: 'var(--f-ui)', fontSize: 13, color: 'var(--c-juniper)', display: 'flex', alignItems: 'center', gap: 8 }}>
                <IconCheck size={16} stroke={2} /> Confirmation emailed to {email || 'your inbox'}
              </div>
            )}
          </div>
          <div style={{ display: 'flex', gap: 10 }}>
            {step > 0 && step < 4 && (
              <button className="btn btn--ghost btn--sm" onClick={() => setStep(s => s - 1)}>Back</button>
            )}
            {step < 3 && (
              <button className="btn btn--primary btn--sm" disabled={!canAdvance}
                      onClick={() => setStep(s => s + 1)}
                      style={{ opacity: canAdvance ? 1 : 0.4 }}>
                Continue <IconArrow size={14} />
              </button>
            )}
            {step === 3 && (
              <button className="btn btn--primary btn--sm" disabled={!canAdvance}
                      onClick={() => setStep(4)}
                      style={{ opacity: canAdvance ? 1 : 0.4 }}>
                Reserve ${total.toLocaleString()} <IconArrow size={14} />
              </button>
            )}
            {step === 4 && (
              <button className="btn btn--primary btn--sm" onClick={onClose}>Done</button>
            )}
          </div>
        </div>
      </div>

      <style>{`
        @media (max-width: 700px) {
          .step-label { display: none; }
        }
      `}</style>
    </div>
  );
}

function StepTour({ tour, setTour }) {
  return (
    <div>
      <p style={{ fontFamily: 'var(--f-body)', color: 'var(--c-mute)', marginTop: 0, marginBottom: 22 }}>
        Which night are you in the mood for?
      </p>
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
        {TOURS.map(t => (
          <button key={t.id} onClick={() => setTour(t)} style={{
            textAlign: 'left',
            padding: 18,
            border: tour.id === t.id ? '2px solid var(--c-ink)' : '1px solid var(--c-line)',
            borderRadius: 14,
            background: tour.id === t.id ? 'var(--c-paper-2)' : 'white',
            display: 'flex',
            gap: 14,
            alignItems: 'flex-start',
            cursor: 'pointer',
            transition: 'all 0.15s ease',
          }}>
            <div style={{
              width: 48, height: 48, borderRadius: 10,
              background: t.gradient, flexShrink: 0,
              display: 'flex', alignItems: 'center', justifyContent: 'center',
              color: 'var(--c-moon)',
            }}>
              <IconStar size={20} stroke={1.4} />
            </div>
            <div style={{ flex: 1 }}>
              <div className="display" style={{ fontSize: 19, marginBottom: 2 }}
                   dangerouslySetInnerHTML={{ __html: t.name }} />
              <div style={{ fontFamily: 'var(--f-body)', fontSize: 13, fontStyle: 'italic', color: 'var(--c-mute)', marginBottom: 8 }}>
                {t.sub}
              </div>
              <div style={{ fontFamily: 'var(--f-ui)', fontSize: 12, color: 'var(--c-mute)' }}>
                {t.duration} · {t.size} · ${t.price}{t.priceUnit ? '' : ' / adult'}
              </div>
            </div>
          </button>
        ))}
      </div>
    </div>
  );
}

function StepDate({ dates, idx, setIdx, tour }) {
  const selected = dates[idx];
  return (
    <div>
      <p style={{ fontFamily: 'var(--f-body)', color: 'var(--c-mute)', marginTop: 0, marginBottom: 22 }}>
        Pick a night. The badge shows what the sky will be best for.
      </p>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(7, 1fr)', gap: 6 }}>
        {dates.map((d, i) => {
          const isDark = d.best.tag === 'Dark Sky Night';
          return (
            <button key={i} onClick={() => setIdx(i)} style={{
              padding: '14px 6px 10px',
              border: idx === i ? '2px solid var(--c-ink)' : '1px solid var(--c-line)',
              borderRadius: 10,
              background: idx === i ? 'var(--c-paper-2)' : 'white',
              display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 6,
              cursor: 'pointer',
            }}>
              <div style={{ fontFamily: 'var(--f-ui)', fontSize: 10, letterSpacing: '0.1em',
                            textTransform: 'uppercase', color: 'var(--c-mute)' }}>
                {d.d.toLocaleDateString('en', { weekday: 'short' })}
              </div>
              <div className="num" style={{ fontSize: 24 }}>{d.d.getDate()}</div>
              <MoonGlyph fraction={d.moon.fraction} size={22} />
              <div style={{
                fontFamily: 'var(--f-ui)', fontSize: 9, fontWeight: 600,
                color: isDark ? 'var(--c-rock)' : 'var(--c-mute)',
                letterSpacing: '0.06em', textTransform: 'uppercase',
              }}>{isDark ? '★ Best' : d.best.tag.replace(' Night','').slice(0,8)}</div>
            </button>
          );
        })}
      </div>

      {selected && (
        <div style={{ marginTop: 24, padding: 20, background: 'var(--c-ink)', color: 'var(--c-star)',
                      borderRadius: 14, display: 'flex', gap: 18, alignItems: 'center' }}>
          <MoonGlyph fraction={selected.moon.fraction} size={56} />
          <div>
            <div className="display" style={{ fontSize: 24, marginBottom: 4 }}>
              {selected.d.toLocaleDateString('en', { weekday: 'long', month: 'long', day: 'numeric' })}
            </div>
            <div style={{ fontFamily: 'var(--f-body)', fontStyle: 'italic', fontSize: 14, color: 'rgba(248,244,232,0.7)' }}>
              {selected.moon.name} · {selected.moon.illum}% illuminated · {selected.best.desc}
            </div>
            <div style={{ fontFamily: 'var(--f-ui)', fontSize: 13, color: 'var(--c-moon)', marginTop: 8 }}>
              ⌛ Tour begins 8:15 PM · Pickup window 8:00–8:10 PM
            </div>
          </div>
        </div>
      )}
    </div>
  );
}

function StepGuests({ tour, adults, setAdults, kids, setKids }) {
  const isPrivate = tour.id === 'private';
  if (isPrivate) {
    return (
      <div>
        <p style={{ fontFamily: 'var(--f-body)', color: 'var(--c-mute)', marginTop: 0, marginBottom: 22 }}>
          Private tour: $1,200 flat for up to 8 guests. Tell us how many to plan for.
        </p>
        <Stepper label="Total in your party" value={adults} setValue={setAdults} min={1} max={8} sub="Includes children" />
      </div>
    );
  }
  return (
    <div>
      <p style={{ fontFamily: 'var(--f-body)', color: 'var(--c-mute)', marginTop: 0, marginBottom: 22 }}>
        Public tours are capped at 10 guests so everyone gets time at the eyepiece.
      </p>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
        <Stepper label="Adults" value={adults} setValue={setAdults} min={0} max={10}
                 sub={`$${tour.price} each`} />
        <Stepper label="Children (ages 5–12)" value={kids} setValue={setKids} min={0} max={10 - adults}
                 sub={`$${tour.childPrice} each`} />
      </div>
      <div style={{ marginTop: 24, padding: 16, background: 'var(--c-paper-2)', borderRadius: 10,
                    fontFamily: 'var(--f-body)', fontSize: 14, fontStyle: 'italic', color: 'var(--c-mute)' }}>
        Under 5? They're welcome — free of charge — if they can stay quiet during constellation talks.
        Please mention them in the notes.
      </div>
    </div>
  );
}

function Stepper({ label, value, setValue, min, max, sub }) {
  return (
    <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center',
                  padding: '16px 20px', border: '1px solid var(--c-line)', borderRadius: 12 }}>
      <div>
        <div style={{ fontFamily: 'var(--f-ui)', fontSize: 15, fontWeight: 600 }}>{label}</div>
        {sub && <div style={{ fontFamily: 'var(--f-ui)', fontSize: 12, color: 'var(--c-mute)', marginTop: 2 }}>{sub}</div>}
      </div>
      <div style={{ display: 'flex', alignItems: 'center', gap: 14 }}>
        <button onClick={() => setValue(Math.max(min, value - 1))} style={{
          width: 36, height: 36, borderRadius: '50%', border: '1px solid var(--c-line)',
          background: 'white', display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
        }}><IconMinus size={14} /></button>
        <div className="num" style={{ fontSize: 22, minWidth: 28, textAlign: 'center' }}>{value}</div>
        <button onClick={() => setValue(Math.min(max, value + 1))} style={{
          width: 36, height: 36, borderRadius: '50%', border: '1px solid var(--c-ink)',
          background: 'var(--c-ink)', color: 'white',
          display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
        }}><IconPlus size={14} /></button>
      </div>
    </div>
  );
}

function StepContact({ name, setName, email, setEmail, phone, setPhone, agree, setAgree }) {
  return (
    <div>
      <p style={{ fontFamily: 'var(--f-body)', color: 'var(--c-mute)', marginTop: 0, marginBottom: 22 }}>
        Where do we send your confirmation, prep guide, and weather updates?
      </p>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
        <div className="field">
          <label>Full name</label>
          <input value={name} onChange={e => setName(e.target.value)} placeholder="Casey Rivera" />
        </div>
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14 }} className="contact-grid">
          <div className="field">
            <label>Email</label>
            <input type="email" value={email} onChange={e => setEmail(e.target.value)} placeholder="casey@example.com" />
          </div>
          <div className="field">
            <label>Mobile phone</label>
            <input type="tel" value={phone} onChange={e => setPhone(e.target.value)} placeholder="(555) 555-5555" />
          </div>
        </div>
        <div className="field">
          <label>Anything we should know? (optional)</label>
          <textarea rows="3" placeholder="Celebrating an anniversary, accessibility needs, kids under 5…"
                    style={{ resize: 'vertical' }} />
        </div>
        <label style={{
          display: 'flex', gap: 12, padding: 16, background: 'var(--c-paper-2)',
          borderRadius: 10, cursor: 'pointer', fontFamily: 'var(--f-body)', fontSize: 14, lineHeight: 1.5,
        }}>
          <input type="checkbox" checked={agree} onChange={e => setAgree(e.target.checked)}
                 style={{ marginTop: 4 }} />
          <span>
            I understand the <a style={{ textDecoration: 'underline' }}>weather &amp; cancellation policy</a> and
            agree to the <a style={{ textDecoration: 'underline' }}>liability waiver</a>. Full refund up to 24
            hours before; weather cancellations are always fully refunded.
          </span>
        </label>
      </div>
      <style>{`@media (max-width: 600px) { .contact-grid { grid-template-columns: 1fr !important; } }`}</style>
    </div>
  );
}

function StepConfirm({ tour, date, adults, kids, name, email, phone, total }) {
  return (
    <div style={{ textAlign: 'center', padding: '8px 0' }}>
      <div style={{
        width: 76, height: 76, borderRadius: '50%',
        background: 'var(--c-rock)',
        color: 'white',
        display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
        marginBottom: 18,
      }}>
        <IconCheck size={32} stroke={2} />
      </div>
      <div className="display" style={{ fontSize: 'clamp(28px, 4vw, 40px)', marginBottom: 12 }}>
        You're <em>booked</em>, {name.split(' ')[0] || 'friend'}.
      </div>
      <p style={{ fontFamily: 'var(--f-body)', color: 'var(--c-mute)', maxWidth: 460, margin: '0 auto 28px', fontStyle: 'italic' }}>
        Confirmation sent to <strong style={{ color: 'var(--c-ink)' }}>{email}</strong>. We'll text you the
        meeting pin and parking note 3 hours before tour time.
      </p>

      <div style={{
        background: 'var(--c-paper-2)', borderRadius: 14, padding: 24, textAlign: 'left',
        maxWidth: 480, margin: '0 auto',
      }}>
        <SummaryRow label="Tour" value={tour.name.replace('&amp;', '&')} />
        <SummaryRow label="Date" value={date ? date.d.toLocaleDateString('en', { weekday: 'long', month: 'long', day: 'numeric' }) : ''} />
        <SummaryRow label="Time" value="Arrive 8:00 PM · Tour 8:15–10:15 PM" />
        <SummaryRow label="Party" value={tour.id === 'private' ? `${adults} guests` : `${adults} adult${adults!==1?'s':''}${kids ? `, ${kids} child` + (kids!==1?'ren':'') : ''}`} />
        <SummaryRow label="Total charged" value={`$${total.toLocaleString()}`} />
      </div>

      <div style={{
        marginTop: 24, fontFamily: 'var(--f-ui)', fontSize: 13, color: 'var(--c-mute)',
        display: 'flex', justifyContent: 'center', gap: 18, flexWrap: 'wrap',
      }}>
        <span style={{ display: 'inline-flex', alignItems: 'center', gap: 6 }}>
          <IconCalendar size={14} /> Add to calendar
        </span>
        <span style={{ display: 'inline-flex', alignItems: 'center', gap: 6 }}>
          <IconJacket size={14} /> Pack list emailed
        </span>
        <span style={{ display: 'inline-flex', alignItems: 'center', gap: 6 }}>
          <IconRoute size={14} /> Directions to follow
        </span>
      </div>
    </div>
  );
}

function SummaryRow({ label, value }) {
  return (
    <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline',
                  padding: '10px 0', borderBottom: '1px dashed var(--c-line)',
                  fontFamily: 'var(--f-ui)', fontSize: 14, gap: 16 }}>
      <span style={{ color: 'var(--c-mute)', letterSpacing: '0.04em', textTransform: 'uppercase', fontSize: 11, fontWeight: 600 }}>{label}</span>
      <span style={{ fontWeight: 500, textAlign: 'right' }}>{value}</span>
    </div>
  );
}

Object.assign(window, { BookingModal });
