/* ============================================================
   Interactive Quote & Booking — multi-step with dynamic pricing
   ============================================================ */

const VEHICLES = [
  { id: 'sedan',  label: 'Sedan',          sub: 'Compact · Mid-size · Hatchback' },
  { id: 'suv',    label: 'SUV',            sub: 'Crossover · 5–7 seat' },
  { id: 'pickup', label: 'Pick-Up',        sub: 'F-150, Silverado…' },
  { id: 'van',    label: 'Van',            sub: 'Sienna, Odyssey…' },
  { id: 'comm',   label: 'Commercial Van', sub: 'Sprinter, Transit' },
  { id: 'truck',  label: 'Trucks',         sub: 'Box truck · Heavy duty' },
];

/* Fixed price matrix (USD). Per-vehicle services use `prices`,
   flat-rate services use `flat`. */
const SERVICES = [
  {
    id: 'regular', label: 'Regular Wash',
    desc: 'Our most common, basic wash — perfect for keeping your vehicle clean.',
    duration: 45,
    prices: { sedan: 50, suv: 80, pickup: 80, van: 99, comm: 159, truck: 199 },
    // Notes shown only when that vehicle is selected.
    vehicleNotes: { pickup: 'If heavily soiled: $100–$120.' },
  },
  {
    id: 'detailing', label: 'Detailing',
    desc: 'Deep interior or exterior cleaning using specialized chemical products for a thorough, professional finish.',
    duration: 150,
    prices: { sedan: 299, suv: 349, pickup: 349, van: 349, comm: 499, truck: 649 },
    note: 'Exterior-only or interior-only: 30% off.',
    vehicleNotes: { pickup: 'If heavily soiled: $499.' },
  },
  {
    id: 'luxury', label: 'Luxury Wash',
    desc: 'Premium service designed for high-end vehicles, with the utmost care and attention to detail.',
    duration: 210,
    flat: 699,
  },
  {
    id: 'headlight', label: 'Headlight Polishing',
    desc: 'We clean and restore the original shine of your headlights, improving both visibility and appearance.',
    duration: 60,
    flat: 99,
  },
];

/* Resolve the price for a service + vehicle. Flat services ignore vehicle. */
const servicePrice = (service, vehicleId) => {
  if (!service) return null;
  if (service.flat != null) return service.flat;
  if (!vehicleId) return null;
  return service.prices?.[vehicleId] ?? null;
};

const PAYMENTS = [
  { id: 'card', label: 'Stripe',          fee: 0.04,  sub: 'Credit / Debit · 4% processing' },
  { id: 'cash', label: 'Cash on Service', fee: -0.10, sub: '10% off paid in person' },
];

const PROMO_CODES = {
  'PRESTIGE10': 0.10,
  'NEWCLIENT15': 0.15,
  'BUILDING5': 0.05,
};

/* Cities we currently service. Booking can only proceed to payment when the
   selected city is one of these. */
const SERVICE_AREAS = [
  'Los Angeles', 'Santa Monica', 'Malibu', 'Beverly Hills', 'West Hollywood',
  'Culver City', 'Marina del Rey', 'Inglewood', 'Hawthorne', 'Manhattan Beach',
  'Torrance', 'Gardena', 'Compton', 'Carson', 'Long Beach', 'Seal Beach',
  'Huntington Beach', 'Anaheim', 'Santa Ana', 'Garden Grove', 'Stanton',
  'Orange', 'Yorba Linda', 'Buena Park', 'Cerritos', 'Lakewood', 'Bellflower',
  'Norwalk', 'Downey', 'South Gate', 'Huntington Park', 'Westmont', 'Whittier',
  'La Mirada', 'La Habra', 'Brea', 'Rowland Heights', 'Hacienda Heights',
  'La Puente', 'Avocado Heights', 'West Covina', 'Covina', 'Glendora', 'Azusa',
  'San Dimas', 'Pomona', 'El Monte', 'Rosemead', 'Alhambra', 'Monterey Park',
  'Montebello', 'Pasadena', 'San Marino', 'Arcadia', 'Altadena',
  'La Cañada Flintridge', 'Glendale', 'Burbank', 'San Fernando', 'Simi Valley',
  'Thousand Oaks', 'Westlake Village', 'Agoura Hills', 'Calabasas',
];
const isServiceableCity = (city) => SERVICE_AREAS.includes(city);

// Helpers
const fmt = (n) => `$${(Math.round(n*100)/100).toFixed(2)}`;
const formatDate = (d) => d.toLocaleDateString('en-US',{weekday:'short',month:'short',day:'numeric'});

// Card input formatting + validation (mock — no real charge until Stripe backend is wired up)
const formatCardNumber = (v) => v.replace(/\D/g,'').slice(0,16).replace(/(.{4})/g,'$1 ').trim();
const formatExp = (v) => { const d = v.replace(/\D/g,'').slice(0,4); return d.length > 2 ? d.slice(0,2)+'/'+d.slice(2) : d; };
const cardIsComplete = (c) =>
  c.number.replace(/\s/g,'').length >= 15 &&
  /^\d{2}\/\d{2}$/.test(c.exp) &&
  c.cvc.length >= 3 &&
  c.name.trim().length > 1;

const Booking = ({ initialServiceId } = {}) => {
  const [step, setStep] = React.useState(0);
  const [vehicle, setVehicle] = React.useState(null);
  const [service, setService] = React.useState(null);
  const [date, setDate] = React.useState(null);
  const [slot, setSlot] = React.useState(null);
  const [addr, setAddr] = React.useState({ line: '', city: '', zip: '', notes: '' });
  const [contact, setContact] = React.useState({ name: '', email: '', phone: '' });
  const [payment, setPayment] = React.useState('card');
  const [promo, setPromo] = React.useState('');
  const [promoApplied, setPromoApplied] = React.useState(null);
  const [card, setCard] = React.useState({ number:'', exp:'', cvc:'', name:'' });
  const [done, setDone] = React.useState(false);
  const [bookingRef, setBookingRef] = React.useState(null);
  const [paying, setPaying] = React.useState(false);
  const [payError, setPayError] = React.useState(null);

  // Returning from Stripe Checkout: ?checkout=success | cancel
  React.useEffect(() => {
    const params = new URLSearchParams(window.location.search);
    const status = params.get('checkout');
    if (!status) return;
    const sessionId = params.get('session_id');
    // Clean the URL so a refresh doesn't re-trigger this.
    window.history.replaceState({}, '', window.location.pathname + '#book');

    const restoreConfirmation = (snap) => {
      if (window.PrestigeStore) window.PrestigeStore.upsert({ ...snap.req, paid: true });
      // Restore enough state to render the confirmation screen.
      setBookingRef(snap.req && snap.req.id ? snap.req.id : null);
      setVehicle(snap.vehicle); setService(snap.service);
      setDate(new Date(snap.date + 'T00:00:00')); setSlot(snap.slot);
      setAddr(snap.addr); setContact(snap.contact);
      setPromoApplied(snap.promoApplied || null);
      setDone(true);
    };

    if (status === 'success' && sessionId) {
      // Never trust the redirect alone — confirm with the server that Stripe was
      // actually paid before marking the booking as paid.
      fetch('api/verify-session.php?session_id=' + encodeURIComponent(sessionId))
        .then(r => r.json())
        .then(v => {
          let snap = null;
          try { snap = JSON.parse(localStorage.getItem('prestige_pending_checkout') || 'null'); } catch (e) {}
          if (v && v.paid && snap) {
            restoreConfirmation(snap);
            // Returning from Stripe lands at the top of the page — bring the
            // confirmation (which lives in the booking section) into view.
            setTimeout(() => {
              const el = document.getElementById('book');
              if (el) el.scrollIntoView({ behavior: 'smooth', block: 'start' });
            }, 150);
          } else {
            setPayError('We could not confirm your payment. If you were charged, please contact us.');
            setStep(STEPS.length - 1); // back to the payment step
          }
        })
        .catch(() => {
          setPayError('We could not verify your payment. Please contact us if you were charged.');
          setStep(STEPS.length - 1);
        })
        .finally(() => {
          localStorage.removeItem('prestige_pending_checkout');
        });
    } else if (status === 'cancel') {
      localStorage.removeItem('prestige_pending_checkout');
      setStep(STEPS.length - 1); // back to the payment step
    }
  }, []);

  // jump to service if requested from elsewhere
  React.useEffect(() => {
    if (initialServiceId) {
      const s = SERVICES.find(s => s.id === initialServiceId);
      if (s) { setService(s); setStep(0); }
    }
  }, [initialServiceId]);

  // Calculate pricing
  const pricing = React.useMemo(() => {
    if (!vehicle || !service) return null;
    const base = servicePrice(service, vehicle.id);
    if (base == null) return null;
    const subtotal = base;
    const promoPct = (promoApplied && PROMO_CODES[promoApplied]) ? PROMO_CODES[promoApplied] : 0;
    const promoAmt = subtotal * promoPct;
    const afterPromo = subtotal - promoAmt;
    const pay = PAYMENTS.find(p => p.id === payment);
    const fee = pay ? afterPromo * pay.fee : 0;
    const total = afterPromo + fee;
    const duration = service.duration;
    return { subtotal, promoPct, promoAmt, fee, total, duration, pay };
  }, [vehicle, service, payment, promoApplied]);

  // Date list — next 14 days
  const dateOptions = React.useMemo(() => {
    const out = [];
    const today = new Date();
    for (let i = 0; i < 14; i++){
      const d = new Date(today.getFullYear(), today.getMonth(), today.getDate()+i);
      out.push(d);
    }
    return out;
  }, []);

  const slots = [
    '7:00 AM','8:00 AM','9:00 AM','10:00 AM','11:00 AM','12:00 PM','1:00 PM',
    '2:00 PM','3:00 PM','4:00 PM','5:00 PM','6:00 PM','7:00 PM',
  ];

  const STEPS = [
    { id: 'vehicle', label: 'Vehicle' },
    { id: 'service', label: 'Service' },
    { id: 'when',    label: 'Date & time' },
    { id: 'where',   label: 'Location' },
    { id: 'pay',     label: 'Review & pay' },
  ];

  const canProceed = () => {
    if (step === 0) return !!vehicle;
    if (step === 1) return !!service;
    if (step === 2) return !!date && !!slot;
    if (step === 3) return addr.line && isServiceableCity(addr.city) && addr.zip && contact.name && contact.email && contact.phone;
    return true;
  };

  const applyPromo = () => {
    const code = promo.trim().toUpperCase();
    if (PROMO_CODES[code]) {
      setPromoApplied(code);
    } else if (code) {
      setPromoApplied('__invalid');
      setTimeout(()=>setPromoApplied(p => p === '__invalid' ? null : p), 1800);
    }
  };

  const submit = () => {
    if (window.PrestigeStore && vehicle && service && date && slot) {
      const PAY = PAYMENTS.find(p => p.id === payment);
      const last4 = payment === 'card' ? card.number.replace(/\s/g,'').slice(-4) : null;
      const req = {
        id: `REQ-${Date.now().toString(36).slice(-4)}-${Math.random().toString(36).slice(2,6).toUpperCase()}`,
        createdAt: new Date().toISOString(),
        status: 'pending',
        paid: payment !== 'cash',
        customer: { name: contact.name, email: contact.email, phone: contact.phone },
        address: { line: addr.line, city: addr.city, zip: addr.zip, notes: addr.notes },
        vehicle: { id: vehicle.id, label: vehicle.label, sub: vehicle.sub },
        service: { id: service.id, label: service.label, duration: service.duration, price: servicePrice(service, vehicle.id) },
        date: window.PrestigeDate.ymd(date),
        slot,
        payment,
        promo: promoApplied,
        pricing: pricing ? {
          subtotal: pricing.subtotal, fee: pricing.fee, total: pricing.total,
          payLabel: (PAY?.label || payment) + (last4 ? ` •••• ${last4}` : ''),
        } : null,
        emailSent: false,
        emailSentAt: null,
        notes: '',
      };
      window.PrestigeStore.upsert(req);
      setBookingRef(req.id);
    }
    setDone(true);
  };

  // Build the booking request object (shared by cash submit + Stripe checkout).
  const buildRequest = (paid) => {
    const PAY = PAYMENTS.find(p => p.id === payment);
    return {
      id: `REQ-${Date.now().toString(36).slice(-4)}-${Math.random().toString(36).slice(2,6).toUpperCase()}`,
      createdAt: new Date().toISOString(),
      status: 'pending',
      paid,
      customer: { name: contact.name, email: contact.email, phone: contact.phone },
      address: { line: addr.line, city: addr.city, zip: addr.zip, notes: addr.notes },
      vehicle: { id: vehicle.id, label: vehicle.label, sub: vehicle.sub },
      service: { id: service.id, label: service.label, duration: service.duration, price: servicePrice(service, vehicle.id) },
      date: window.PrestigeDate.ymd(date),
      slot,
      payment,
      promo: promoApplied,
      pricing: pricing ? {
        subtotal: pricing.subtotal, fee: pricing.fee, total: pricing.total,
        payLabel: PAY?.label || payment,
      } : null,
      emailSent: false, emailSentAt: null, notes: '',
    };
  };

  // Card payment: create a Stripe Checkout Session on the server, then redirect.
  const startCheckout = async () => {
    if (!vehicle || !service || !date || !slot || !pricing) return;
    setPayError(null);
    setPaying(true);
    try {
      // Stash a snapshot so we can show the confirmation when Stripe redirects back.
      const req = buildRequest(false);
      const snapshot = { req, vehicle, service, date: window.PrestigeDate.ymd(date), slot, addr, contact, promoApplied };
      localStorage.setItem('prestige_pending_checkout', JSON.stringify(snapshot));

      const res = await fetch('api/create-checkout-session.php', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          vehicleId: vehicle.id,
          serviceId: service.id,
          promo: promoApplied || '',
          email: contact.email,
          label: `${service.label} — ${vehicle.label}`,
          reference: req.id,
        }),
      });
      const data = await res.json().catch(() => ({}));
      if (!res.ok || !data.url) throw new Error(data.error || 'We could not start the payment. Please try again.');
      window.location.href = data.url;
    } catch (e) {
      localStorage.removeItem('prestige_pending_checkout');
      setPaying(false);
      setPayError(e.message || 'Payment could not be started. Please try again.');
    }
  };

  if (done) return <BookingConfirmation
    vehicle={vehicle} service={service} date={date} slot={slot}
    addr={addr} contact={contact} pricing={pricing} reference={bookingRef}
    onReset={()=>{
      setStep(0); setVehicle(null); setService(null); setDate(null); setSlot(null);
      setAddr({line:'',city:'',zip:'',notes:''}); setContact({name:'',email:'',phone:''});
      setPromo(''); setPromoApplied(null); setCard({number:'',exp:'',cvc:'',name:''}); setDone(false); setBookingRef(null);
    }}
  />;

  return (
    <section id="book" className="section booking-section booking-section-feature">
      <div className="booking-aura" aria-hidden></div>
      <div className="container">
        <div className="section-head section-head-feature">
          <span className="eyebrow">Book your service</span>
          <h2>Book in <span className="gold-text">under a minute.</span></h2>
          <p>Pick your vehicle, pick a service — see your price instantly.</p>
        </div>

        <div className="booking-shell booking-shell-feature">
          <div className="gold-corner tl"></div>
          <div className="gold-corner tr"></div>
          <div className="gold-corner bl"></div>
          <div className="gold-corner br"></div>
          {/* Stepper */}
          <div className="stepper">
            {STEPS.map((s, i) => (
              <button
                key={s.id}
                className={`stepper-item ${i === step ? 'is-active' : ''} ${i < step ? 'is-done' : ''}`}
                onClick={() => i <= step + 1 && (canProceed() || i <= step) && setStep(i)}
              >
                <span className="stepper-num mono">{String(i+1).padStart(2,'0')}</span>
                <span className="stepper-label">{s.label}</span>
              </button>
            ))}
          </div>

          <div className="booking-body">
            <div className="booking-main">
              {step === 0 && <StepVehicle vehicle={vehicle} setVehicle={setVehicle} />}
              {step === 1 && <StepService service={service} setService={setService} vehicle={vehicle}/>}
              {step === 2 && <StepWhen
                dateOptions={dateOptions} date={date} setDate={setDate}
                slots={slots} slot={slot} setSlot={setSlot}
              />}
              {step === 3 && <StepWhere addr={addr} setAddr={setAddr} contact={contact} setContact={setContact} />}
              {step === 4 && <StepPay
                payment={payment} setPayment={setPayment}
                card={card} setCard={setCard}
                promo={promo} setPromo={setPromo}
                promoApplied={promoApplied} setPromoApplied={setPromoApplied}
                applyPromo={applyPromo}
              />}

              <div className="booking-actions">
                {step > 0 && (
                  <button className="btn btn-dark" onClick={()=>setStep(s=>s-1)}>
                    ← Back
                  </button>
                )}
                <div className="booking-actions-spacer"/>
                {step < STEPS.length - 1 && (
                  <button
                    className="btn btn-primary"
                    disabled={!canProceed()}
                    onClick={()=>canProceed() && setStep(s=>s+1)}
                  >
                    Continue <Icon name="arrow" size={14}/>
                  </button>
                )}
                {step === STEPS.length - 1 && (
                  <button
                    className="btn btn-primary"
                    disabled={paying || (payment === 'card' && !pricing)}
                    onClick={payment === 'cash' ? submit : startCheckout}
                  >
                    {paying
                      ? 'Redirecting to Stripe…'
                      : payment === 'cash'
                        ? 'Confirm booking'
                        : `Pay ${pricing ? fmt(pricing.total) : ''} & confirm`} <Icon name="arrow" size={14}/>
                  </button>
                )}
              </div>
              {payError && (
                <div className="mono" style={{color:'#e07b7b',fontSize:12,marginTop:10,textAlign:'right'}}>{payError}</div>
              )}
            </div>

            <BookingSummary
              vehicle={vehicle} service={service} date={date} slot={slot}
              addr={addr} pricing={pricing} promoApplied={promoApplied}
            />
          </div>
        </div>

        <div className="booking-extras">
          <div className="booking-extras-row">
            <div className="booking-extra">
              <div className="booking-extra-icon"><Icon name="shield" size={22}/></div>
              <div>
                <strong>Secure payments</strong>
                <span>Stripe · Cash on service</span>
              </div>
            </div>
            <div className="booking-extra">
              <div className="booking-extra-icon"><Icon name="clock" size={22}/></div>
              <div>
                <strong>Free cancellation</strong>
                <span>Up to 4 hours before your appointment</span>
              </div>
            </div>
            <div className="booking-extra">
              <div className="booking-extra-icon"><Icon name="sparkle" size={22}/></div>
              <div>
                <strong>Satisfaction guaranteed</strong>
                <span>We&rsquo;ll make it right if you&rsquo;re not happy</span>
              </div>
            </div>
          </div>

          <div className="booking-extras-cta">
            <span className="mono">Prefer to talk to a human?</span>
            <a href="tel:+14244150208" className="booking-call">
              <Icon name="phone" size={16}/> (424) 415-0208
            </a>
          </div>
        </div>
      </div>
    </section>
  );
};

/* ---- Step 1: Vehicle ------------------------------------- */
const StepVehicle = ({ vehicle, setVehicle }) => (
  <div className="step-pane">
    <h3>Select your vehicle type</h3>
    <p className="step-help">Pricing scales with vehicle size. Choose the option that best matches yours.</p>
    <div className="vehicle-grid">
      {VEHICLES.map(v => (
        <button
          key={v.id}
          className={`vehicle-card ${vehicle?.id === v.id ? 'is-active' : ''}`}
          onClick={()=>setVehicle(v)}
        >
          <VehicleSilhouette type={v.id}/>
          <div className="vehicle-card-meta">
            <div className="vehicle-card-label">{v.label}</div>
            <div className="vehicle-card-sub">{v.sub}</div>
          </div>
        </button>
      ))}
    </div>
  </div>
);

const VehicleSilhouette = ({ type }) => {
  const files = {
    sedan:  'sedan.svg',
    suv:    'suv.svg',
    pickup: 'pickup.svg',
    van:    'vanfamily.svg',
    comm:   'comercial.svg',
    truck:  'pickup.svg', // no dedicated truck asset yet — reuses pickup silhouette
  };
  return (
    <div className="vehicle-silhouette">
      <img src={`assets/${files[type]}`} alt={type} />
    </div>
  );
};

/* ---- Step 2: Service ------------------------------------- */
const StepService = ({ service, setService, vehicle }) => (
  <div className="step-pane">
    <h3>Choose your service</h3>
    <p className="step-help">All services scaled to your <strong style={{color:'var(--gold-2)'}}>{vehicle?.label || 'vehicle'}</strong>. Prices update automatically.</p>
    <div className="service-grid-form">
      {SERVICES.map(s => {
        const price = servicePrice(s, vehicle?.id);
        return (
          <button
            key={s.id}
            className={`service-row ${service?.id === s.id ? 'is-active' : ''}`}
            onClick={()=>setService(s)}
          >
            <div className="service-row-radio">
              {service?.id === s.id ? <Icon name="check" size={14}/> : null}
            </div>
            <div className="service-row-meta">
              <div className="service-row-label">{s.label}</div>
              <div className="service-row-desc">{s.desc}</div>
              {s.note && <div className="service-row-desc" style={{color:'var(--gold-2)'}}>{s.note}</div>}
              {s.vehicleNotes?.[vehicle?.id] && <div className="service-row-desc" style={{color:'var(--gold-2)'}}>{s.vehicleNotes[vehicle.id]}</div>}
              <div className="service-row-meta-line mono">
                <span><Icon name="clock" size={12}/> ~{s.duration}m</span>
              </div>
            </div>
            <div className="service-row-price">
              {price !== null ? (
                <>
                  <div className="serif gold-text" style={{fontSize:28}}>${price}</div>
                  {s.flat != null && (
                    <div className="mono" style={{fontSize:10,color:'var(--muted-2)',letterSpacing:'0.2em'}}>FLAT RATE</div>
                  )}
                </>
              ) : '—'}
            </div>
          </button>
        );
      })}
    </div>
  </div>
);

/* ---- Step 3: When ---------------------------------------- */
const StepWhen = ({ dateOptions, date, setDate, slots, slot, setSlot }) => {
  const [taken, setTaken] = React.useState(new Set());

  React.useEffect(() => {
    const refresh = () => {
      if (!date || !window.PrestigeStore) { setTaken(new Set()); return; }
      setTaken(window.PrestigeStore.takenSlotsForDate(date));
    };
    refresh();
    window.addEventListener('prestige:requests-changed', refresh);
    return () => window.removeEventListener('prestige:requests-changed', refresh);
  }, [date]);

  return (
    <div className="step-pane">
      <h3>Pick a date &amp; time</h3>
      <p className="step-help">Real-time availability for our mobile crew across LA. Booked slots are locked.</p>

      <div className="field-label">DATE</div>
      <div className="date-row">
        {dateOptions.map((d, i) => {
          const isSel = date && d.toDateString() === date.toDateString();
          return (
            <button key={i} className={`date-pill ${isSel ? 'is-active' : ''}`} onClick={()=>setDate(d)}>
              <span className="mono date-dow">{d.toLocaleDateString('en-US',{weekday:'short'}).toUpperCase()}</span>
              <span className="serif date-day">{d.getDate()}</span>
              <span className="mono date-mo">{d.toLocaleDateString('en-US',{month:'short'}).toUpperCase()}</span>
            </button>
          );
        })}
      </div>

      <div className="field-label" style={{marginTop:32}}>TIME SLOT</div>
      <div className="slot-row">
        {slots.map(s => {
          const isTaken = taken.has(s);
          const isActive = slot === s;
          return (
            <button
              key={s}
              className={`slot-pill ${isActive ? 'is-active' : ''} ${isTaken ? 'is-taken' : ''}`}
              onClick={() => { if (!isTaken) setSlot(s); }}
              disabled={isTaken}
              title={isTaken ? 'This slot is already booked' : ''}
            >
              {s}
              {isTaken && <span className="slot-pill-tag mono">Booked</span>}
            </button>
          );
        })}
      </div>
    </div>
  );
};

/* ---- Step 4: Where --------------------------------------- */
const StepWhere = ({ addr, setAddr, contact, setContact }) => (
  <div className="step-pane">
    <h3>Where should we meet you?</h3>
    <p className="step-help">Home, office, garage, hotel — wherever you'll have your vehicle parked.</p>

    <div className="form-grid">
      <div className="field" style={{gridColumn:'span 2'}}>
        <label className="field-label">Street address</label>
        <input className="input" placeholder="8500 Sunset Blvd" value={addr.line} onChange={e=>setAddr({...addr,line:e.target.value})}/>
      </div>
      <div className="field">
        <label className="field-label">City</label>
        <select className="input" value={addr.city} onChange={e=>setAddr({...addr,city:e.target.value})}>
          <option value="">Select your city…</option>
          {SERVICE_AREAS.map(c => <option key={c} value={c}>{c}</option>)}
        </select>
        {addr.city && !isServiceableCity(addr.city) && (
          <div className="field-label" style={{color:'var(--gold-2)',marginTop:6}}>Sorry — we don't service this city yet.</div>
        )}
      </div>
      <div className="field">
        <label className="field-label">ZIP</label>
        <input className="input" placeholder="90069" value={addr.zip} onChange={e=>setAddr({...addr,zip:e.target.value})}/>
      </div>
      <div className="field" style={{gridColumn:'span 2'}}>
        <label className="field-label">Notes for the crew (optional)</label>
        <input className="input" placeholder="Garage code, access instructions, water spigot location…" value={addr.notes} onChange={e=>setAddr({...addr,notes:e.target.value})}/>
      </div>

      <div className="field-divider" style={{gridColumn:'span 2'}}><span>YOUR CONTACT</span></div>

      <div className="field">
        <label className="field-label">Full name</label>
        <input className="input" placeholder="Edgar Ramirez" value={contact.name} onChange={e=>setContact({...contact,name:e.target.value})}/>
      </div>
      <div className="field">
        <label className="field-label">Phone</label>
        <input className="input" placeholder="(424) 415-0208" value={contact.phone} onChange={e=>setContact({...contact,phone:e.target.value})}/>
      </div>
      <div className="field" style={{gridColumn:'span 2'}}>
        <label className="field-label">Email</label>
        <input className="input" placeholder="you@email.com" value={contact.email} onChange={e=>setContact({...contact,email:e.target.value})}/>
      </div>
    </div>
  </div>
);

/* ---- Step 5: Pay ----------------------------------------- */
const StepPay = ({ payment, setPayment, card, setCard, promo, setPromo, promoApplied, applyPromo }) => (
  <div className="step-pane">
    <h3>Choose how to pay</h3>
    <p className="step-help">Pay securely online — or pay in person on the day for a 10% discount.</p>

    <div className="pay-grid">
      {PAYMENTS.map(p => (
        <button
          key={p.id}
          className={`pay-card ${payment === p.id ? 'is-active' : ''}`}
          onClick={()=>setPayment(p.id)}
        >
          <div className="pay-card-radio">{payment === p.id ? <Icon name="check" size={14}/> : null}</div>
          <div className="pay-card-label">{p.label}</div>
          <div className="pay-card-sub">{p.sub}</div>
        </button>
      ))}
    </div>

    {payment === 'card' && (
      <div className="card-form" style={{marginTop:24}}>
        <div className="field-divider"><span>SECURE CHECKOUT</span></div>
        <div style={{fontSize:14,color:'var(--ivory)',marginTop:16,lineHeight:1.6}}>
          When you confirm, you'll be taken to Stripe's secure checkout to enter your card and complete payment — then brought right back here.
        </div>
        <div className="mono" style={{fontSize:11,color:'var(--muted-2)',marginTop:12,display:'flex',alignItems:'center',gap:6}}>
          <Icon name="shield" size={12}/> Secured by Stripe — your card details never touch our servers.
        </div>
      </div>
    )}

    <div className="promo-row">
      <div className="field" style={{flex:1}}>
        <label className="field-label">Promo code</label>
        <div style={{display:'flex',gap:8}}>
          <input
            className="input"
            placeholder="e.g. PRESTIGE10"
            value={promo}
            onChange={e=>setPromo(e.target.value)}
            onKeyDown={e=>{if(e.key==='Enter') applyPromo();}}
          />
          <button className="btn btn-dark" style={{padding:'14px 20px'}} onClick={applyPromo}>Apply</button>
        </div>
        {promoApplied === '__invalid' && (
          <div className="mono" style={{fontSize:11,color:'#e07b7b'}}>Code not recognized.</div>
        )}
        {promoApplied && promoApplied !== '__invalid' && (
          <div className="mono" style={{fontSize:11,color:'var(--gold-2)'}}>
            ✓ {promoApplied} applied · {(PROMO_CODES[promoApplied]*100).toFixed(0)}% off
          </div>
        )}
      </div>
    </div>

    <div className="terms">
      <Icon name="shield" size={16}/>
      <span>You'll only be charged after the service is confirmed by our crew. Card payments processed via Stripe.</span>
    </div>
  </div>
);

/* ---- Sticky summary -------------------------------------- */
const BookingSummary = ({ vehicle, service, date, slot, addr, pricing, promoApplied }) => (
  <aside className="booking-summary">
    <div className="gold-corner tl"></div>
    <div className="gold-corner tr"></div>
    <div className="gold-corner bl"></div>
    <div className="gold-corner br"></div>

    <div className="summary-head">
      <span className="eyebrow">Your quote</span>
      <h3 style={{fontSize:20}}>Booking summary</h3>
    </div>

    <div className="summary-rows">
      <SummaryRow label="Vehicle" value={vehicle?.label} sub={vehicle?.sub}/>
      <SummaryRow label="Service" value={service?.label} sub={service?.desc}/>
      <SummaryRow label="When" value={date ? formatDate(date) : null} sub={slot}/>
      <SummaryRow label="Location" value={addr.line || null} sub={addr.city ? `${addr.city}${addr.zip ? ', '+addr.zip : ''}` : null}/>
      <SummaryRow label="Estimated duration" value={pricing ? `~${pricing.duration} minutes` : null}/>
    </div>

    <div className="gold-rule" style={{margin:'24px 0'}}/>

    {pricing ? (
      <div className="price-block">
        <div className="price-line"><span>Subtotal</span><span>{fmt(pricing.subtotal)}</span></div>
        {promoApplied && promoApplied !== '__invalid' && (
          <div className="price-line gold"><span>Promo {promoApplied}</span><span>−{fmt(pricing.promoAmt)}</span></div>
        )}
        <div className="price-line muted">
          <span>{pricing.pay?.label} fee {pricing.pay?.fee >= 0 ? '+' : ''}{(pricing.pay?.fee*100).toFixed(0)}%</span>
          <span>{pricing.fee >= 0 ? '' : '−'}{fmt(Math.abs(pricing.fee))}</span>
        </div>
        <div className="gold-rule" style={{margin:'16px 0'}}/>
        <div className="price-total">
          <span className="mono">TOTAL</span>
          <span className="serif gold-text">{fmt(pricing.total)}</span>
        </div>
      </div>
    ) : (
      <div className="price-empty">
        <Icon name="sparkle" size={18}/>
        <p>Choose a vehicle and service to see your live quote.</p>
      </div>
    )}

    <div className="summary-trust">
      <div><Icon name="shield" size={14}/> Secure</div>
      <div><Icon name="clock" size={14}/> Instant</div>
      <div><Icon name="check" size={14}/> No hidden fees</div>
    </div>
  </aside>
);

const SummaryRow = ({ label, value, sub }) => (
  <div className="summary-row">
    <span className="mono summary-row-label">{label}</span>
    <div className="summary-row-val">
      <div>{value || <span className="muted">—</span>}</div>
      {sub && <div className="summary-row-sub">{sub}</div>}
    </div>
  </div>
);

/* ---- Confirmation ---------------------------------------- */
const BookingConfirmation = ({ vehicle, service, date, slot, addr, contact, pricing, reference, onReset }) => (
  <section id="book" className="section booking-section">
    <div className="container">
      <div className="confirm-shell">
        <div className="gold-corner tl"></div>
        <div className="gold-corner tr"></div>
        <div className="gold-corner bl"></div>
        <div className="gold-corner br"></div>

        <div className="confirm-icon">
          <Icon name="check" size={32}/>
        </div>
        <span className="eyebrow" style={{justifyContent:'center'}}>Booking confirmed</span>
        <h2 style={{textAlign:'center'}}>You're on the calendar,<br/><span className="gold-text">{contact.name?.split(' ')[0] || 'friend'}.</span></h2>
        <p style={{textAlign:'center',maxWidth:520,margin:'0 auto',color:'var(--muted)'}}>
          A confirmation has been sent to <strong style={{color:'var(--ivory)'}}>{contact.email || 'your email'}</strong>.
          Our crew will text you 30 minutes before arrival.
        </p>

        <div className="confirm-grid">
          <div><span className="mono">Reference</span><strong className="serif">{reference || '—'}</strong></div>
          <div><span className="mono">Vehicle</span><strong>{vehicle?.label}</strong></div>
          <div><span className="mono">Service</span><strong>{service?.label}</strong></div>
          <div><span className="mono">When</span><strong>{date && formatDate(date)} · {slot}</strong></div>
          <div><span className="mono">Where</span><strong>{addr.line}, {addr.city}</strong></div>
          <div><span className="mono">Total charged</span><strong className="gold-text">{fmt(pricing.total)}</strong></div>
        </div>

        <div className="confirm-actions">
          <button className="btn btn-primary" onClick={onReset}>Book another service</button>
          <a className="btn btn-ghost" href="#top">Back to top</a>
        </div>
      </div>
    </div>
  </section>
);

window.Booking = Booking;
window.SERVICES = SERVICES;
