/* Booking modal — multi-step flow */
const { useState, useEffect, useMemo } = React;
const BBIcon = window.BBComponents.Icon;

function BookingModal({ open, onClose }){
  const [step, setStep] = useState(0);
  const [plan, setPlan] = useState(null);
  const [date, setDate] = useState(null);
  const [time, setTime] = useState(null);
  const [info, setInfo] = useState({ name: '', email: '', phone: '', address: '', city: 'Halifax', notes: '' });
  const [confirmed, setConfirmed] = useState(false);
  const [refId, setRefId] = useState('');
  const [submitting, setSubmitting] = useState(false);
  const [error, setError] = useState('');

  useEffect(() => {
    if (open) {
      // reset on each open
      setStep(0); setPlan(null); setDate(null); setTime(null);
      setInfo({ name: '', email: '', phone: '', address: '', city: 'Halifax', notes: '' });
      setConfirmed(false);
      document.body.style.overflow = 'hidden';
    } else {
      document.body.style.overflow = '';
    }
    return () => { document.body.style.overflow = ''; };
  }, [open]);

  // Build next 6 weekday-ish dates
  const dates = useMemo(() => {
    const out = [];
    const start = new Date(); start.setHours(0,0,0,0);
    let d = new Date(start);
    d.setDate(d.getDate() + 2);
    while (out.length < 6) {
      const dow = d.getDay();
      if (dow !== 0 && dow !== 6) {
        out.push(new Date(d));
      }
      d.setDate(d.getDate() + 1);
    }
    return out;
  }, [open]);

  const times = ['8:00 AM', '10:00 AM', '12:30 PM', '2:30 PM', '4:30 PM'];

  const plans = [
    { id: 'single', icon: 'home',  title: 'Single head',    desc: 'One indoor unit. Most apartments and condos.', price: '$179' },
    { id: 'two',    icon: 'snow',  title: 'Two heads',      desc: 'Two indoor units, same address.',             price: '$299' },
    { id: 'whole',  icon: 'shield',title: 'Whole home',     desc: '3+ heads. We confirm after a quick photo.',   price: 'From $419' },
    { id: 'tune',   icon: 'sparkle', title: 'Maintenance tune-up', desc: 'Filter rinse + visual check, no deep clean.', price: '$89' }
  ];

  const canNext = (
    (step === 0 && plan) ||
    (step === 1 && date && time) ||
    (step === 2 && info.name && info.email && info.phone && info.address) ||
    (step === 3)
  );

  const next = () => {
    if (step < 2) setStep(step + 1);
    else if (step === 2) {
      setSubmitting(true);
      setError('');
      const SvcPlan = plans.find(p => p.id === plan);
      const payload = {
        name: info.name,
        email: info.email,
        phone: info.phone,
        address: info.address,
        city: info.city,
        plan: SvcPlan ? (SvcPlan.id === 'single' ? 'Single head ($179)' : SvcPlan.id === 'two' ? 'Two heads ($299)' : SvcPlan.id === 'whole' ? 'Whole home ($419)' : 'Tune-up ($89)') : 'Single head ($179)',
        date: date.toISOString().split('T')[0],
        time: time,
        notes: info.notes || ''
      };
      fetch('https://bluebear-booking.djorourke.workers.dev', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(payload)
      })
      .then(r => r.json())
      .then(data => {
        if (data.success) {
          setRefId(data.ref);
          setConfirmed(true);
          setStep(3);
        } else {
          setError(data.error || 'Something went wrong. Try again.');
        }
      })
      .catch(() => setError('Unable to reach booking. Check your connection.'))
      .finally(() => setSubmitting(false));
    } else onClose();
  };

  const back = () => { if (step > 0 && !confirmed) setStep(step - 1); };

  const selectedPlan = plans.find(p => p.id === plan);
  const fmtDate = (d) => d?.toLocaleDateString('en-CA', { weekday: 'short', month: 'short', day: 'numeric' });

  return (
    <div className={`modal-backdrop ${open ? 'open' : ''}`} onClick={(e) => { if (e.target === e.currentTarget) onClose(); }}>
      <div className="modal" role="dialog" aria-modal="true" aria-label="Book a cleaning">
        <div className="modal-head">
          <div className="step-dots" aria-hidden="true">
            {[0,1,2,3].map(i => (
              <span key={i} className={i === step ? 'active' : (i < step ? 'done' : '')}/>
            ))}
          </div>
          <button className="modal-close" onClick={onClose} aria-label="Close">
            <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.4" strokeLinecap="round"><line x1="6" y1="6" x2="18" y2="18"/><line x1="6" y1="18" x2="18" y2="6"/></svg>
          </button>
        </div>

        <div className="modal-body">
          {step === 0 && (
            <>
              <h3>What are we cleaning?</h3>
              <p className="sub">Pick what fits your home. You can always change this later.</p>
              <div className="option-list">
                {plans.map(p => (
                  <button key={p.id} className={`option ${plan === p.id ? 'selected' : ''}`} onClick={() => setPlan(p.id)}>
                    <span className="opt-icon"><BBIcon name={p.icon}/></span>
                    <span className="opt-body">
                      <div className="opt-title">{p.title}</div>
                      <div className="opt-desc">{p.desc}</div>
                    </span>
                    <span className="opt-price">{p.price}</span>
                  </button>
                ))}
              </div>
            </>
          )}

          {step === 1 && (
            <>
              <h3>Choose your preferred day &amp; arrival window</h3>
              <p className="sub">Tell us what works best for you. We'll confirm the exact appointment before anything is booked.</p>
              <div className="date-grid">
                {dates.map((d, i) => (
                  <button key={i} className={`date-pill ${date && d.toDateString() === date.toDateString() ? 'selected' : ''}`} onClick={() => setDate(new Date(d))}>
                    <div className="dow">{d.toLocaleDateString('en-CA', { weekday: 'short' })}</div>
                    <div className="day">{d.getDate()}</div>
                    <div className="mo">{d.toLocaleDateString('en-CA', { month: 'short' })}</div>
                  </button>
                ))}
              </div>
              <div style={{ fontWeight: 600, fontSize: 14, color: 'var(--ink)', marginBottom: 8 }}>Arrival window</div>
              <div className="time-row">
                {times.map(t => (
                  <button key={t} className={`time-pill ${time === t ? 'selected' : ''}`} onClick={() => setTime(t)}>{t}</button>
                ))}
              </div>
            </>
          )}

          {step === 2 && (
            <>
              <h3>Where should we come?</h3>
              <p className="sub">We'll send a confirmation email and a friendly reminder the day before.</p>
              {error && <div style={{ background: '#fef2f2', color: '#991b1b', padding: '10px 14px', borderRadius: 8, marginBottom: 14, fontSize: 14 }}>{error}</div>}
              <div className="field-row">
                <div className="field">
                  <label>Full name</label>
                  <input type="text" value={info.name} onChange={e => setInfo({ ...info, name: e.target.value })} placeholder="Your name"/>
                </div>
                <div className="field">
                  <label>Phone</label>
                  <input type="tel" value={info.phone} onChange={e => setInfo({ ...info, phone: e.target.value })} placeholder="(902) 555-0123"/>
                </div>
              </div>
              <div className="field">
                <label>Email</label>
                <input type="email" value={info.email} onChange={e => setInfo({ ...info, email: e.target.value })} placeholder="you@home.ca"/>
              </div>
              <div className="field-row">
                <div className="field">
                  <label>Address</label>
                  <input type="text" value={info.address} onChange={e => setInfo({ ...info, address: e.target.value })} placeholder="123 Spring Garden Rd"/>
                </div>
                <div className="field">
                  <label>City</label>
                  <select value={info.city} onChange={e => setInfo({ ...info, city: e.target.value })}>
                    {['Halifax','Dartmouth','Bedford','Sackville','Cole Harbour','Fall River','Eastern Passage','Outside our zone'].map(c =>
                      <option key={c}>{c}</option>
                    )}
                  </select>
                </div>
              </div>
              <div className="field">
                <label>Anything we should know? <span style={{ fontWeight: 400, color: 'var(--muted)' }}>(optional)</span></label>
                <textarea rows="3" value={info.notes} onChange={e => setInfo({ ...info, notes: e.target.value })} placeholder="Pets, parking notes, unit access, smells you're noticing…"/>
              </div>
            </>
          )}

          {step === 3 && (
            <div className="confirm-card">
              <div className="ring">
                <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="3" strokeLinecap="round" strokeLinejoin="round"><polyline points="20 6 9 17 4 12"/></svg>
              </div>
              <h3>Booked. We'll see you soon.</h3>
              <p className="sub">A confirmation is on its way to <strong style={{ color: 'var(--ink)' }}>{info.email || 'your inbox'}</strong>.</p>
              <div className="ref">{refId}</div>
              <div className="recap">
                <div className="recap-row"><span className="l">Service</span><span className="v">{selectedPlan?.title} — {selectedPlan?.price}</span></div>
                <div className="recap-row"><span className="l">Date</span><span className="v">{fmtDate(date)}</span></div>
                <div className="recap-row"><span className="l">Arrival window</span><span className="v">{time}</span></div>
                <div className="recap-row"><span className="l">Address</span><span className="v">{info.address}, {info.city}</span></div>
              </div>
              <p style={{ marginTop: 18, fontSize: 13, color: 'var(--muted)' }}>
                No payment today. We collect after the visit. Need to change something? Reply to your confirmation email.
              </p>
            </div>
          )}
        </div>

        <div className="modal-foot">
          <div className="modal-summary">
            {confirmed ? (
              <>Reference <strong>{refId}</strong></>
            ) : (
              <>
                {selectedPlan && <><strong>{selectedPlan.title}</strong> · {selectedPlan.price}</>}
                {selectedPlan && date && <> · {fmtDate(date)}</>}
                {selectedPlan && date && time && <> · {time}</>}
                {!selectedPlan && <>Step {step + 1} of 3</>}
              </>
            )}
          </div>
          <div style={{ display: 'flex', gap: 8 }}>
            {step > 0 && !confirmed && <button className="btn btn-ghost btn-sm" onClick={back}>Back</button>}
            <button className="btn btn-primary btn-sm" onClick={next} disabled={!canNext || submitting} style={!canNext || submitting ? { opacity: .5, cursor: 'not-allowed' } : {}}>
              {confirmed ? 'Done' : submitting ? 'Submitting...' : step === 2 ? 'Confirm booking' : 'Continue'}
            </button>
          </div>
        </div>
      </div>
    </div>
  );
}

window.BookingModal = BookingModal;
