// Public booking flow → creates the customer account on confirmation.
// Steps: Service → When (day + slot) → Vehicle → Who → Confirmation.
// On success, we set a portal session and link the user to My Garage.

const STORE_KEY     = 'iag_admin_v1';
const CUST_AUTH_KEY = 'iag_customer_auth';

// ---------- Store helpers ----------
function loadStore() {
  try {
    const raw = localStorage.getItem(STORE_KEY);
    return raw ? JSON.parse(raw) : null;
  } catch { return null; }
}
function saveStore(s) { localStorage.setItem(STORE_KEY, JSON.stringify(s)); }

function minimalStore() {
  return {
    bookings: [], customers: [], vehicles: [], invoices: [],
    subscribers: [], reviews: [], templates: [], campaigns: [], automations: [],
    activity: [],
    content: window.getSiteContent ? window.getSiteContent() : { hero: {}, hours: [], services: [] },
    settings: {
      password: 'garage',
      shopName: 'Infinite Auto Garage',
      taxRate: 7.0,
      bookingSlotMinutes: 60,
      bays: [
        { id: 1, name: 'Bay 1', tech: 'Devin' },
        { id: 2, name: 'Bay 2', tech: 'Marcus' },
        { id: 3, name: 'Bay 3', tech: 'Luis' },
      ],
      bookingServices: [
        'Diagnostics', 'Brake Service', 'Oil Changes', 'Engine Repair',
        'AC Service', 'Suspension & Steering', 'Electrical Repair',
        'Preventive Maintenance', 'Pre-Purchase Inspection', 'Other / Not Sure',
      ],
      emailFrom: 'service@infiniteautogarage.com',
      notifications: { newBookingEmail: true, newSubscriberEmail: false, dailyDigest: true },
    },
  };
}

const last4 = (phone) => (phone || '').replace(/\D/g, '').slice(-4);
const uid = (p = 'x') => p + '-' + Math.random().toString(36).slice(2, 8);

function findOrCreateCustomer(store, { name, email, phone }) {
  const norm = (s) => (s || '').trim().toLowerCase();
  const existing = store.customers.find(c => norm(c.email) === norm(email) && norm(email));
  if (existing) {
    existing.name  = existing.name  || name;
    existing.phone = existing.phone || phone;
    return existing;
  }
  const fresh = {
    id: uid('c'),
    name: name.trim(),
    email: email.trim().toLowerCase(),
    phone: phone.trim(),
    city: '', tags: ['new'],
    createdAt: new Date().toISOString(),
    notes: '',
  };
  store.customers.push(fresh);
  return fresh;
}

function findOrCreateVehicle(store, customerId, v) {
  if (!v || !v.year || !v.make || !v.model) return null;
  const sameOwner = store.vehicles.filter(x => x.customerId === customerId);
  const match = sameOwner.find(x =>
    x.year === Number(v.year) &&
    x.make.toLowerCase() === v.make.trim().toLowerCase() &&
    x.model.toLowerCase() === v.model.trim().toLowerCase()
  );
  if (match) {
    if (v.vin && !match.vin) match.vin = v.vin.toUpperCase();
    return match;
  }
  const fresh = {
    id: uid('v'),
    customerId,
    year: Number(v.year),
    make: v.make.trim(),
    model: v.model.trim(),
    vin: v.vin ? v.vin.toUpperCase() : '',
    plate: '',
    miles: 0,
    color: '',
  };
  store.vehicles.push(fresh);
  return fresh;
}

function saveBookingToStore({ service, whenIso, bay, name, email, phone, vehicle, notes }) {
  let store = loadStore();
  const wasFresh = !store;
  if (!store) store = minimalStore();

  const customer = findOrCreateCustomer(store, { name, email, phone });
  const vehicleRec = findOrCreateVehicle(store, customer.id, vehicle);

  const booking = {
    id: uid('b'),
    customerId: customer.id,
    vehicleId: vehicleRec?.id || '',
    service,
    when: whenIso,
    bay: bay || 1,
    status: 'confirmed',
    tech: store.settings.bays.find(b => b.id === bay)?.tech || '',
    notes: notes || '',
    createdAt: new Date().toISOString(),
  };
  store.bookings.push(booking);
  store.activity.unshift({
    id: uid('ac'),
    when: booking.createdAt,
    type: 'booking',
    msg: `New booking — ${customer.name}, ${service}${vehicleRec ? ` (${vehicleRec.year} ${vehicleRec.make})` : ''}${wasFresh ? ' · first customer!' : ''}`,
  });

  saveStore(store);

  // Mirror to Firestore so the booking is visible to the owner from any
  // device. Best-effort — failures are logged but the localStorage copy
  // still saved above, so the customer sees confirmation either way.
  if (window.IAG && window.IAG.createBooking) {
    window.IAG.createBooking({
      service,
      when: whenIso,
      bay: bay || 1,
      customer: { name, email, phone },
      vehicle: vehicleRec ? { year: vehicleRec.year, make: vehicleRec.make, model: vehicleRec.model, vin: vehicleRec.vin || '' } : null,
      notes: notes || '',
      source: 'public',
    }).then((firestoreId) => {
      // Stash the Firestore id on the local copy so admin reconciliation
      // can match them up later.
      try {
        const s2 = loadStore();
        const b = s2?.bookings.find(x => x.id === booking.id);
        if (b) { b.firestoreId = firestoreId; saveStore(s2); }
      } catch (e) {}
    }).catch((e) => {
      console.warn('[BookingModal] Firestore mirror failed (booking still saved locally):', e?.message || e);
    });
  }

  return { customer, booking, vehicle: vehicleRec };
}

// ---------- Date / slot helpers ----------
const fmtTime = (iso) => new Date(iso).toLocaleTimeString(undefined, { hour: 'numeric', minute: '2-digit' });
const dayMap = ['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday'];

function nextOpenDays(count = 14) {
  const content = window.getSiteContent ? window.getSiteContent() : null;
  const hours = content?.hours || [];
  const isOpen = (dow) => {
    const row = hours.find(h => h.day === dayMap[dow]);
    return row && !row.closed;
  };
  const out = [];
  let i = 0;
  while (out.length < count && i < 28) {
    const d = new Date(); d.setHours(0,0,0,0); d.setDate(d.getDate() + i);
    if (isOpen(d.getDay())) out.push(d);
    i++;
  }
  return out;
}

function generateSlotsForDay(d) {
  const store   = loadStore();
  const content = window.getSiteContent ? window.getSiteContent() : null;
  const hours   = content?.hours || store?.content?.hours || [];
  const slotMin = store?.settings?.bookingSlotMinutes || 60;
  const bays    = store?.settings?.bays || [{ id: 1, name: 'Bay 1', tech: '' }];

  const row = hours.find(h => h.day === dayMap[d.getDay()]);
  if (!row || row.closed) return [];
  const [oh, om] = (row.open  || '08:00').split(':').map(Number);
  const [ch, cm] = (row.close || '18:00').split(':').map(Number);

  const taken = new Set((store?.bookings || []).filter(b => b.status !== 'cancelled').map(b => `${b.when}|${b.bay}`));
  const slots = [];
  const openMin  = oh * 60 + om;
  const closeMin = ch * 60 + cm;
  for (let m = openMin; m + slotMin <= closeMin; m += slotMin) {
    const slot = new Date(d); slot.setHours(0, m, 0, 0);
    if (slot.getTime() < Date.now() + 60 * 60 * 1000) continue; // skip past slots
    const iso = slot.toISOString();
    const freeBay = bays.find(b => !taken.has(`${iso}|${b.id}`));
    if (freeBay) slots.push({ iso, bayId: freeBay.id, bayName: freeBay.name, tech: freeBay.tech });
  }
  return slots;
}

// ---------- Modal ----------
const TOTAL_STEPS = 4;

const BookingModal = ({ open, onClose }) => {
  const [step, setStep]               = React.useState(1);
  const [service, setService]         = React.useState('');
  const [dayIso, setDayIso]           = React.useState('');
  const [slot, setSlot]               = React.useState(null);
  const [vehicle, setVehicle]         = React.useState({ year: '', make: '', model: '', vin: '' });
  const [skipVehicle, setSkipVehicle] = React.useState(false);
  const [notes, setNotes]             = React.useState('');
  const [name, setName]               = React.useState('');
  const [email, setEmail]             = React.useState('');
  const [phone, setPhone]             = React.useState('');
  const [emailErr, setEmailErr]       = React.useState('');
  const [phoneErr, setPhoneErr]       = React.useState('');
  const [result, setResult]           = React.useState(null);
  const [isReturning, setIsReturning] = React.useState(false);
  const [existingVehicles, setExistingVehicles] = React.useState([]);
  const [pickedVehicleId, setPickedVehicleId]   = React.useState('');

  React.useEffect(() => {
    if (open) {
      setStep(1);
      setService(''); setDayIso(''); setSlot(null);
      setVehicle({ year: '', make: '', model: '', vin: '' });
      setSkipVehicle(false);
      setNotes('');
      setName(''); setEmail(''); setPhone('');
      setEmailErr(''); setPhoneErr('');
      setResult(null); setIsReturning(false);
      setExistingVehicles([]); setPickedVehicleId('');
    }
  }, [open]);

  React.useEffect(() => {
    if (result?.customer?.id) {
      try {
        localStorage.setItem(CUST_AUTH_KEY, JSON.stringify({ customerId: result.customer.id }));
      } catch {}
    }
  }, [result]);

  // Memos that need to be above the early return
  const services = React.useMemo(() => {
    const s = loadStore();
    return s?.settings?.bookingServices || ['Diagnostics', 'Oil Changes', 'Brake Service', 'Engine Repair', 'AC Service', 'Other'];
  }, [open]);
  const days = React.useMemo(() => nextOpenDays(14), [open]);
  const slots = React.useMemo(() => {
    if (!dayIso) return [];
    return generateSlotsForDay(new Date(dayIso + 'T00:00:00'));
  }, [dayIso]);

  // Auto-pick the first existing vehicle when we detect a returning customer.
  // MUST stay above the early return for stable hook order.
  React.useEffect(() => {
    if (existingVehicles.length && !pickedVehicleId && !vehicle.make) {
      setPickedVehicleId(existingVehicles[0].id);
    }
  }, [existingVehicles, pickedVehicleId, vehicle.make]);

  if (!open) return null;

  const validateEmail = (em) => /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(em.trim());
  const validatePhone = (ph) => ph.replace(/\D/g, '').length >= 10;

  // Detect returning customer when email is committed (blur or 'change' with @)
  const checkReturning = (em) => {
    const norm = em.trim().toLowerCase();
    if (!norm.includes('@')) { setIsReturning(false); setExistingVehicles([]); return; }
    const store = loadStore();
    const found = store?.customers.find(c => c.email.toLowerCase() === norm);
    if (found) {
      setIsReturning(true);
      if (!name)  setName(found.name);
      if (!phone) setPhone(found.phone);
      const vs = store.vehicles.filter(v => v.customerId === found.id);
      setExistingVehicles(vs);
    } else {
      setIsReturning(false);
      setExistingVehicles([]);
    }
  };

  const submitVehicleFromForm = () => {
    // Vehicle form data is in `vehicle` state already
    return skipVehicle ? null : vehicle;
  };

  const confirm = () => {
    setEmailErr(''); setPhoneErr('');
    if (!validateEmail(email)) { setEmailErr('Need a valid email.'); return; }
    if (!validatePhone(phone)) { setPhoneErr('Need a 10-digit phone.'); return; }
    let vehicleToSave = null;
    if (pickedVehicleId) {
      // Returning customer picked an existing vehicle
      const store = loadStore();
      const v = store?.vehicles.find(x => x.id === pickedVehicleId);
      if (v) vehicleToSave = { year: v.year, make: v.make, model: v.model, vin: v.vin };
    } else if (!skipVehicle && vehicle.year && vehicle.make && vehicle.model) {
      vehicleToSave = vehicle;
    }
    const r = saveBookingToStore({
      service,
      whenIso: slot.iso,
      bay: slot.bayId,
      name: name.trim(),
      email: email.trim().toLowerCase(),
      phone: phone.trim(),
      vehicle: vehicleToSave,
      notes: notes.trim(),
    });
    setResult(r);
    setStep(5);
  };

  return (
    <div className="modal-backdrop" onClick={onClose}
      style={{
        position: 'fixed', inset: 0, zIndex: 100,
        background: 'rgba(0,0,0,0.78)',
        backdropFilter: 'blur(8px)', WebkitBackdropFilter: 'blur(8px)',
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        padding: 32, overflowY: 'auto',
      }}>
      <div className="modal" onClick={(e) => e.stopPropagation()}
        style={{
          background: 'var(--iag-ink-1, #0B0C0F)',
          border: '1px solid var(--iag-ink-4, #282C34)',
          borderRadius: 16,
          width: '100%', maxWidth: 560,
          padding: '36px 36px 32px',
          boxShadow: '0 60px 120px -40px rgba(0,0,0,0.9), inset 0 1px 0 rgba(255,255,255,0.06)',
          position: 'relative',
          margin: 'auto',
        }}>
        <button className="modal-close" onClick={onClose} aria-label="Close"
          style={{
            position: 'absolute', top: 16, right: 16,
            width: 36, height: 36, borderRadius: 999,
            background: 'var(--iag-ink-2, #14161B)',
            border: '1px solid var(--iag-ink-4, #282C34)',
            color: 'var(--fg-secondary, #DDE0E5)',
            cursor: 'pointer',
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            padding: 0, zIndex: 2,
          }}>
          <IconClose size={16} />
        </button>

        {step <= TOTAL_STEPS && (
          <div className="steps-dots">
            {Array.from({ length: TOTAL_STEPS }, (_, i) => (
              <span key={i} className={step >= i + 1 ? 'active' : ''} />
            ))}
          </div>
        )}

        {/* STEP 1 — SERVICE */}
        {step === 1 && (
          <>
            <div className="modal-eyebrow">STEP 01 · SERVICE</div>
            <h2>What's the<br/>job?</h2>
            <p className="modal-sub">Pick what you need. Not sure? Pick "Diagnostics" — we'll figure it out.</p>
            <div className="svc-choice">
              {services.slice(0, 8).map((s, i) => (
                <button key={s} className={service === s ? 'sel' : ''} onClick={() => setService(s)}>
                  <span className="k">SVC-{String(i + 1).padStart(2, '0')}</span>
                  {s}
                </button>
              ))}
            </div>
            <button
              className="btn btn-primary btn-lg"
              style={{ marginTop: 26, width: '100%', justifyContent: 'center', opacity: service ? 1 : 0.4, pointerEvents: service ? 'auto' : 'none' }}
              onClick={() => setStep(2)}
            >
              Continue <IconArrow size={18} />
            </button>
          </>
        )}

        {/* STEP 2 — WHEN: day + slot */}
        {step === 2 && (
          <>
            <div className="modal-eyebrow">STEP 02 · WHEN</div>
            <h2>Pick a day &amp; time.</h2>
            <p className="modal-sub">Available slots for the next two weeks — based on our open hours.</p>

            <div className="bm-day-strip">
              {days.map((d) => {
                const iso = d.toISOString().slice(0, 10);
                const dow = d.toLocaleDateString(undefined, { weekday: 'short' }).toUpperCase();
                const mon = d.toLocaleDateString(undefined, { month: 'short' }).toUpperCase();
                return (
                  <button key={iso} className={`bm-day-chip ${dayIso === iso ? 'is-on' : ''}`}
                          onClick={() => { setDayIso(iso); setSlot(null); }}>
                    <span className="d-dow">{dow}</span>
                    <span className="d-num">{d.getDate()}</span>
                    <span className="d-mon">{mon}</span>
                  </button>
                );
              })}
            </div>

            {dayIso && (
              <div className="bm-slot-grid">
                {slots.length === 0 ? (
                  <div className="bm-no-slots">No open slots that day. Try another.</div>
                ) : slots.map(s => (
                  <button key={s.iso + s.bayId}
                          className={`bm-slot-chip ${slot?.iso === s.iso && slot?.bayId === s.bayId ? 'is-on' : ''}`}
                          onClick={() => setSlot(s)}>
                    <span className="t">{fmtTime(s.iso)}</span>
                    <span className="b">{s.bayName}{s.tech ? ` · ${s.tech}` : ''}</span>
                  </button>
                ))}
              </div>
            )}

            <div style={{display:'flex', gap:10, marginTop:24}}>
              <button className="btn btn-ghost btn-lg" style={{flex:1, justifyContent:'center'}} onClick={() => setStep(1)}>Back</button>
              <button
                className="btn btn-primary btn-lg"
                style={{ flex: 2, justifyContent: 'center', opacity: slot ? 1 : 0.4, pointerEvents: slot ? 'auto' : 'none' }}
                onClick={() => setStep(3)}
              >
                Continue <IconArrow size={18} />
              </button>
            </div>
          </>
        )}

        {/* STEP 3 — VEHICLE */}
        {step === 3 && (
          <>
            <div className="modal-eyebrow">STEP 03 · VEHICLE</div>
            <h2>What are<br/>we working on?</h2>
            <p className="modal-sub">Tells the tech what parts to pull before you arrive. Optional but helpful.</p>

            {existingVehicles.length > 0 ? (
              <>
                <div className="bm-veh-picker">
                  {existingVehicles.map(v => (
                    <button key={v.id}
                            className={`bm-veh-card ${pickedVehicleId === v.id ? 'is-on' : ''}`}
                            onClick={() => { setPickedVehicleId(v.id); setSkipVehicle(false); }}>
                      <div className="bm-veh-yr">{v.year}</div>
                      <div className="bm-veh-mk">{v.make}</div>
                      <div className="bm-veh-md">{v.model}</div>
                    </button>
                  ))}
                  <button className={`bm-veh-card bm-veh-add ${pickedVehicleId === '__new' ? 'is-on' : ''}`}
                          onClick={() => { setPickedVehicleId('__new'); setSkipVehicle(false); }}>
                    <span style={{fontSize:22}}>+</span>
                    <span style={{fontSize:11,letterSpacing:'0.16em',marginTop:6}}>ANOTHER CAR</span>
                  </button>
                </div>
                {pickedVehicleId === '__new' && (
                  <VehicleForm vehicle={vehicle} setVehicle={setVehicle} />
                )}
              </>
            ) : (
              <VehicleForm vehicle={vehicle} setVehicle={setVehicle} />
            )}

            <div className="form-field" style={{marginTop: 16}}>
              <label>
                Anything we should know? <span style={{color:'var(--iag-steel-500)', textTransform:'none', letterSpacing:0, fontFamily:'var(--font-sans)', marginLeft: 4}}>optional</span>
              </label>
              <textarea
                value={notes}
                onChange={(e) => setNotes(e.target.value)}
                placeholder="Noises, warning lights, drop-off preferences, what to focus on…"
                rows={3}
                style={{
                  width: '100%',
                  background: 'var(--iag-ink-3)',
                  border: '1px solid var(--iag-ink-4)',
                  borderRadius: 10,
                  padding: '12px 14px',
                  fontFamily: 'var(--font-sans)',
                  fontSize: 14,
                  color: 'var(--fg)',
                  resize: 'vertical',
                  minHeight: 70,
                  lineHeight: 1.5,
                }}
              />
            </div>

            <div style={{display:'flex', gap:10, marginTop:18}}>
              <button className="btn btn-ghost btn-lg" style={{flex:1, justifyContent:'center'}} onClick={() => setStep(2)}>Back</button>
              <button
                className="btn btn-primary btn-lg"
                style={{ flex: 2, justifyContent: 'center' }}
                onClick={() => {
                  // Validate: either picked an existing vehicle, OR filled in year+make+model, OR explicitly skipping
                  if (pickedVehicleId && pickedVehicleId !== '__new') { setStep(4); return; }
                  if (vehicle.year && vehicle.make && vehicle.model) { setStep(4); return; }
                  // Allow skipping silently — clear pickedVehicleId so we don't save existing
                  setSkipVehicle(true);
                  setPickedVehicleId('');
                  setStep(4);
                }}
              >
                Continue <IconArrow size={18} />
              </button>
            </div>
            <button className="bm-skip-link"
                    onClick={() => { setSkipVehicle(true); setPickedVehicleId(''); setVehicle({ year: '', make: '', model: '', vin: '' }); setStep(4); }}>
              Skip — I'll add my car later
            </button>
          </>
        )}

        {/* STEP 4 — WHO */}
        {step === 4 && (
          <>
            <div className="modal-eyebrow">STEP 04 · WHO</div>
            <h2>How do we<br/>reach you?</h2>
            <p className="modal-sub">
              {isReturning
                ? "Welcome back — we'll attach this to your account."
                : "We'll save your info so you can manage this booking online — no password to remember."}
            </p>
            <div className="form-field">
              <label>Your name</label>
              <input value={name} onChange={(e) => setName(e.target.value)} placeholder="Alex Reyes" autoComplete="name" />
            </div>
            <div className="form-field">
              <label>Email {isReturning && <span style={{color:'var(--iag-volt)',marginLeft:6}}>· Returning customer</span>}</label>
              <input type="email" inputMode="email" autoComplete="email"
                     value={email}
                     onChange={(e) => { setEmail(e.target.value); setEmailErr(''); if (e.target.value.includes('@')) checkReturning(e.target.value); }}
                     onBlur={(e) => checkReturning(e.target.value)}
                     placeholder="you@email.com" />
              {emailErr && <div style={{fontSize:12, color:'var(--iag-danger)', marginTop:4}}>{emailErr}</div>}
            </div>
            <div className="form-field">
              <label>Phone</label>
              <input type="tel" inputMode="tel" autoComplete="tel"
                     value={phone}
                     onChange={(e) => { setPhone(e.target.value); setPhoneErr(''); }}
                     placeholder="(239) 555-0123" />
              {phoneErr && <div style={{fontSize:12, color:'var(--iag-danger)', marginTop:4}}>{phoneErr}</div>}
            </div>
            <p className="modal-fine" style={{
              fontSize:11, color:'var(--iag-steel-500)',
              fontFamily:'var(--font-mono)', letterSpacing:'0.08em',
              margin:'-4px 0 16px', lineHeight: 1.6,
            }}>
              By booking you agree we may text you the confirmation. We don't share your info. Sign back in to the portal with a code we email you.
            </p>
            <div style={{display:'flex', gap:10}}>
              <button className="btn btn-ghost btn-lg" style={{flex:1, justifyContent:'center'}} onClick={() => setStep(3)}>Back</button>
              <button
                className="btn btn-primary btn-lg"
                style={{
                  flex: 2, justifyContent: 'center',
                  opacity: (name && email && phone) ? 1 : 0.4,
                  pointerEvents: (name && email && phone) ? 'auto' : 'none',
                }}
                onClick={confirm}
              >
                Confirm booking <IconCheck size={18} />
              </button>
            </div>
          </>
        )}

        {/* STEP 5 — CONFIRMATION + ACCOUNT */}
        {step === 5 && result && (
          <div className="success-blk">
            <div className="check"><IconCheck size={32} strokeWidth={2.5} /></div>
            <div className="modal-eyebrow" style={{color:'var(--iag-success)'}}>BOOKED · {result.booking.tech ? `BAY ${result.booking.bay} · ${result.booking.tech.toUpperCase()}` : `BAY ${result.booking.bay}`}</div>
            <h2>You're on<br/>the schedule.</h2>
            <p className="modal-sub" style={{maxWidth: 380, margin: '0 auto 22px'}}>
              {isReturning
                ? "We've added this to your account."
                : "We just created your account so you can manage this any time."}
            </p>

            <div className="booking-recap">
              <div className="recap-row">
                <span>Service</span>
                <b>{result.booking.service}</b>
              </div>
              <div className="recap-row">
                <span>When</span>
                <b>{new Date(result.booking.when).toLocaleDateString(undefined, { weekday: 'short', month: 'short', day: 'numeric' })}, {fmtTime(result.booking.when)}</b>
              </div>
              {result.vehicle && (
                <div className="recap-row">
                  <span>Vehicle</span>
                  <b>{result.vehicle.year} {result.vehicle.make} {result.vehicle.model}</b>
                </div>
              )}
              {result.booking.notes && (
                <div className="recap-row recap-notes">
                  <span>Your notes</span>
                  <b style={{whiteSpace:'pre-wrap', textAlign:'right', maxWidth:'70%'}}>{result.booking.notes}</b>
                </div>
              )}
              <div className="recap-row recap-ref">
                <span>Confirmation</span>
                <b className="mono">IAG-{result.booking.id.slice(-4).toUpperCase()}</b>
              </div>
            </div>

            <div className="account-card">
              <div className="account-mono">YOUR SIGN-IN — KEEP THIS HANDY</div>
              <div className="account-creds">
                <div><span>EMAIL</span><b>{result.customer.email}</b></div>
                <div><span>LAST 4 OF PHONE</span><b className="mono big">{last4(result.customer.phone)}</b></div>
              </div>
              <p className="account-note">
                {isReturning
                  ? `Welcome back, ${result.customer.name.split(' ')[0]}. Pick up where you left off.`
                  : `That's it — no password to remember. Use these next time to view, reschedule, or cancel any booking.`}
              </p>
            </div>

            <a href={`customer.html?signin=${encodeURIComponent(result.customer.id)}`} className="btn btn-primary btn-lg" style={{
              width:'100%', justifyContent:'center', textDecoration:'none', marginTop: 16,
            }}>
              Open My Garage <IconArrow size={18} />
            </a>
            <button className="modal-secondary" onClick={onClose} style={{
              marginTop: 14, background:'transparent', border:'none',
              fontFamily:'var(--font-mono)', fontSize:11, letterSpacing:'0.16em', textTransform:'uppercase',
              color:'var(--iag-steel-400)', cursor:'pointer', width:'100%', padding:'8px',
            }}>
              Or close and stay on the page
            </button>
          </div>
        )}
      </div>
    </div>
  );
};

// Vehicle form — used by step 3
const VehicleForm = ({ vehicle, setVehicle }) => {
  const set = (k, v) => setVehicle(prev => ({ ...prev, [k]: v }));
  const yearOptions = React.useMemo(() => {
    const yr = new Date().getFullYear();
    const out = [];
    for (let y = yr + 1; y >= 1985; y--) out.push(y);
    return out;
  }, []);
  return (
    <div className="bm-veh-form">
      <div className="bm-veh-grid">
        <div className="form-field">
          <label>Year</label>
          <select value={vehicle.year} onChange={(e) => set('year', e.target.value)}>
            <option value="">—</option>
            {yearOptions.map(y => <option key={y}>{y}</option>)}
          </select>
        </div>
        <div className="form-field">
          <label>Make</label>
          <input value={vehicle.make} onChange={(e) => set('make', e.target.value)} placeholder="Toyota" />
        </div>
        <div className="form-field">
          <label>Model</label>
          <input value={vehicle.model} onChange={(e) => set('model', e.target.value)} placeholder="Tacoma" />
        </div>
      </div>
      <div className="form-field">
        <label>VIN <span style={{color:'var(--iag-steel-500)', textTransform:'none', letterSpacing:0, fontFamily:'var(--font-sans)', marginLeft: 4}}>optional · 17 chars</span></label>
        <input value={vehicle.vin} onChange={(e) => set('vin', e.target.value.toUpperCase().slice(0,17))} placeholder="1HGCV1F30KA987232" maxLength={17} />
      </div>
    </div>
  );
};

window.BookingModal = BookingModal;
