/* SAYFAYA — Booking flow (React) */
const { useState, useMemo, useEffect } = React;

/* ---------- Data ---------- */
const PACKAGES = [
  { id: 'express', name: 'Express Valet', price: 79, time: '45–60 min',
    desc: 'Fast interior refresh between deep cleans.',
    icon: 'M13 2 3 14h7l-1 8 10-12h-7l1-8z' },
  { id: 'deep', name: 'Interior Deep Clean', price: 149, time: '2–3 hrs', popular: true,
    desc: 'Steam, shampoo & extraction — the full reset.',
    icon: 'CAR' },
  { id: 'full', name: 'Full Detail', price: 229, time: '3–4 hrs',
    desc: 'Inside & out. The complete transformation.',
    icon: 'WHEEL' },
];

const VEHICLES = [
  { id: 'sedan', name: 'Coupe / Sedan', surcharge: 0, desc: 'Up to 5 seats' },
  { id: 'suv', name: 'SUV / Crossover', surcharge: 30, desc: 'Compact to mid-size' },
  { id: 'truck', name: 'Truck / Minivan / 7-seater', surcharge: 50, desc: 'Large vehicles' },
];

const ADDONS = [
  { id: 'pet', name: 'Pet hair removal', price: 40, note: 'Embedded fur lift' },
  { id: 'ozone', name: 'Ozone odour treatment', price: 50, note: 'Smoke & pet odours' },
  { id: 'ceramic', name: 'Interior ceramic coating', price: 90, note: 'Stain protection' },
  { id: 'headlight', name: 'Headlight restoration', price: 60, note: 'Clears hazing' },
  { id: 'engine', name: 'Engine bay cleaning', price: 45, note: 'Under the hood' },
  { id: 'leather', name: 'Leather conditioning', price: 35, note: 'Restore & protect' },
];

const CITIES = ['Halifax', 'Dartmouth', 'Bedford', 'Sackville', 'Moncton', 'Other (nearby)'];
const TIME_SLOTS = ['8:00 AM', '9:30 AM', '11:00 AM', '12:30 PM', '2:00 PM', '3:30 PM', '5:00 PM'];
const STEPS = ['Package', 'Vehicle', 'Date & time', 'Details', 'Confirm'];
const MONTHS = ['January','February','March','April','May','June','July','August','September','October','November','December'];
const DOW = ['Su','Mo','Tu','We','Th','Fr','Sa'];

/* ---------- Icons ---------- */
const Check = ({ w = 14 }) => (
  <svg width={w} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.6"><path d="M20 6 9 17l-5-5"/></svg>
);
const Arrow = () => (
  <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2"><path d="M5 12h14M13 6l6 6-6 6"/></svg>
);
function PkgIcon({ icon }) {
  if (icon === 'CAR') return <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M3 13l2-6a3 3 0 0 1 2.8-2h8.4A3 3 0 0 1 19 7l2 6"/><path d="M5 17h14M6 17v2M18 17v2M4 13h16v4H4z"/><circle cx="7.5" cy="15" r="1"/><circle cx="16.5" cy="15" r="1"/></svg>;
  if (icon === 'WHEEL') return <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><circle cx="12" cy="12" r="9"/><path d="M12 3a9 9 0 0 1 0 18M7 9c1.5-1.5 8.5-1.5 10 0M7 15c1.5 1.5 8.5 1.5 10 0"/></svg>;
  return <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d={icon}/></svg>;
}

/* ---------- Helpers ---------- */
const money = (n) => '$' + n.toLocaleString('en-CA');
const sameDay = (a, b) => a && b && a.toDateString() === b.toDateString();
const fmtDate = (d) => d ? d.toLocaleDateString('en-CA', { weekday: 'long', month: 'long', day: 'numeric' }) : '';

/* ---------- Stepper ---------- */
function Stepper({ step }) {
  return (
    <div className="stepper">
      {STEPS.map((s, i) => (
        <React.Fragment key={s}>
          <div className={'stp ' + (i === step ? 'active' : i < step ? 'done' : '')}>
            <div className="stp-dot">{i < step ? <Check /> : i + 1}</div>
            <div className="stp-lab">{s}</div>
          </div>
          {i < STEPS.length - 1 && <div className={'stp-line ' + (i < step ? 'fill' : '')} />}
        </React.Fragment>
      ))}
    </div>
  );
}

/* ---------- Calendar ---------- */
function Calendar({ selected, onSelect }) {
  const today = useMemo(() => { const d = new Date(); d.setHours(0,0,0,0); return d; }, []);
  const [view, setView] = useState(() => new Date(today.getFullYear(), today.getMonth(), 1));
  const maxDate = useMemo(() => { const d = new Date(today); d.setDate(d.getDate() + 60); return d; }, [today]);

  const year = view.getFullYear(), month = view.getMonth();
  const firstDow = new Date(year, month, 1).getDay();
  const daysIn = new Date(year, month + 1, 0).getDate();
  const cells = [];
  for (let i = 0; i < firstDow; i++) cells.push(null);
  for (let d = 1; d <= daysIn; d++) cells.push(new Date(year, month, d));

  const prevDisabled = year === today.getFullYear() && month === today.getMonth();
  const nextDisabled = new Date(year, month + 1, 1) > maxDate;

  return (
    <div>
      <div className="cal-head">
        <b>{MONTHS[month]} {year}</b>
        <div className="cal-nav">
          <button onClick={() => setView(new Date(year, month - 1, 1))} disabled={prevDisabled} aria-label="Previous month">
            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M15 6l-6 6 6 6"/></svg>
          </button>
          <button onClick={() => setView(new Date(year, month + 1, 1))} disabled={nextDisabled} aria-label="Next month">
            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M9 6l6 6-6 6"/></svg>
          </button>
        </div>
      </div>
      <div className="dow">{DOW.map(d => <span key={d}>{d}</span>)}</div>
      <div className="cal-grid">
        {cells.map((d, i) => {
          if (!d) return <button key={i} className="day empty" disabled />;
          const isSun = d.getDay() === 0;
          const past = d < today;
          const tooFar = d > maxDate;
          const disabled = isSun || past || tooFar;
          return (
            <button key={i}
              className={'day ' + (sameDay(d, selected) ? 'sel ' : '') + (sameDay(d, today) ? 'today' : '')}
              disabled={disabled}
              onClick={() => onSelect(d)}>
              {d.getDate()}
            </button>
          );
        })}
      </div>
    </div>
  );
}

/* ---------- Summary ---------- */
function Summary({ pkg, vehicle, addons, date, time, total }) {
  return (
    <aside className="summary">
      <h3>Your booking</h3>
      <div className="sm-sub">No deposit — pay on completion</div>

      <div className={'sm-row ' + (pkg ? '' : 'empty')}>
        <span className="l">Package</span>
        <span className="v">{pkg ? pkg.name : 'Not selected'}</span>
      </div>
      <div className={'sm-row ' + (vehicle ? '' : 'empty')}>
        <span className="l">Vehicle</span>
        <span className="v">{vehicle ? vehicle.name : '—'}{vehicle && vehicle.surcharge > 0 ? ' (+' + money(vehicle.surcharge) + ')' : ''}</span>
      </div>
      {addons.length > 0 && (
        <div className="sm-addons">
          {addons.map(a => (
            <div className="sa" key={a.id}><span>{a.name}</span><span>{money(a.price)}</span></div>
          ))}
        </div>
      )}
      <div className={'sm-row ' + (date ? '' : 'empty')}>
        <span className="l">Date</span>
        <span className="v">{date ? date.toLocaleDateString('en-CA', { month: 'short', day: 'numeric' }) : '—'}</span>
      </div>
      <div className={'sm-row ' + (time ? '' : 'empty')}>
        <span className="l">Time</span>
        <span className="v">{time || '—'}</span>
      </div>

      <div className="sm-total">
        <span className="l">Estimated total</span>
        <span className="v">{pkg ? money(total) : '—'}</span>
      </div>
      <p className="sm-note">Final price is confirmed on-site and depends on vehicle condition. Taxes extra.</p>

      <div className="sm-trust">
        <div><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"/></svg>Fully insured &amp; police-checked</div>
        <div><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M3 12a9 9 0 1 0 18 0 9 9 0 0 0-18 0z"/><path d="M12 7v5l3 2"/></svg>Free reschedule up to 24h before</div>
        <div><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M20 6 9 17l-5-5"/></svg>Satisfaction guaranteed</div>
      </div>
    </aside>
  );
}

/* ---------- Main App ---------- */
function BookingApp() {
  const [step, setStep] = useState(0);
  const [pkgId, setPkgId] = useState(() => new URLSearchParams(location.search).get('pkg') || '');
  const [vehId, setVehId] = useState('');
  const [addonIds, setAddonIds] = useState([]);
  const [date, setDate] = useState(null);
  const [time, setTime] = useState('');
  const [form, setForm] = useState({ name: '', phone: '', email: '', address: '', city: 'Halifax', notes: '' });
  const [errors, setErrors] = useState({});

  const pkg = PACKAGES.find(p => p.id === pkgId) || null;
  const vehicle = VEHICLES.find(v => v.id === vehId) || null;
  const addons = ADDONS.filter(a => addonIds.includes(a.id));
  const total = (pkg ? pkg.price : 0) + (vehicle ? vehicle.surcharge : 0) + addons.reduce((s, a) => s + a.price, 0);

  useEffect(() => { window.scrollTo({ top: 0, behavior: 'smooth' }); }, [step]);

  const toggleAddon = (id) => setAddonIds(ids => ids.includes(id) ? ids.filter(x => x !== id) : [...ids, id]);
  const setField = (k, v) => { setForm(f => ({ ...f, [k]: v })); setErrors(e => ({ ...e, [k]: undefined })); };

  const canNext = () => {
    if (step === 0) return !!pkg;
    if (step === 1) return !!vehicle;
    if (step === 2) return !!date && !!time;
    if (step === 3) return validateForm(false);
    return true;
  };
  function validateForm(commit) {
    const e = {};
    if (!form.name.trim()) e.name = 'Required';
    if (!/^[\d\s().+-]{7,}$/.test(form.phone)) e.phone = 'Enter a valid phone';
    if (!/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(form.email)) e.email = 'Enter a valid email';
    if (!form.address.trim()) e.address = 'Required';
    if (commit) setErrors(e);
    return Object.keys(e).length === 0;
  }

  const next = () => {
    if (step === 3) { if (!validateForm(true)) return; }
    setStep(s => Math.min(s + 1, 5));
  };
  const back = () => setStep(s => Math.max(s - 1, 0));

  const confirmationId = useMemo(() => 'SY-' + Math.random().toString(36).slice(2, 7).toUpperCase(), []);

  /* ----- Confirmation screen ----- */
  if (step === 5) {
    return (
      <div className="book-shell">
        <div className="book-main" style={{ maxWidth: 720, margin: '0 auto' }}>
          <div className="confirm">
            <div className="confirm-ic"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.4"><path d="M20 6 9 17l-5-5"/></svg></div>
            <h2>You're booked in!</h2>
            <p>Thanks, {form.name.split(' ')[0]}. We've sent a confirmation to {form.email} and a reminder will follow the day before.</p>
            <div className="confirm-card">
              <div className="cc-row"><span className="l">Confirmation</span><span className="v">{confirmationId}</span></div>
              <div className="cc-row"><span className="l">Service</span><span className="v">{pkg.name}</span></div>
              <div className="cc-row"><span className="l">When</span><span className="v">{fmtDate(date)} · {time}</span></div>
              <div className="cc-row"><span className="l">Where</span><span className="v">{form.city}</span></div>
              <div className="cc-row"><span className="l">Estimated total</span><span className="v">{money(total)}</span></div>
            </div>
            <div className="confirm-actions">
              <a className="btn btn--gold" href="index.html">Back to home</a>
              <a className="btn btn--ghost" href="tel:+19024147827">Call us with a question</a>
            </div>
          </div>
        </div>
      </div>
    );
  }

  return (
    <div className="book-shell">
      <div className="book-head">
        <span className="eyebrow eyebrow--center" style={{ justifyContent: 'center' }}>Book online</span>
        <h1>Reserve your detail</h1>
        <p>Under a minute. No deposit. We come to you.</p>
      </div>

      <Stepper step={step} />

      <div className="book-grid">
        <div className="book-main">

          {/* STEP 0 — Package */}
          {step === 0 && (
            <div>
              <h2 className="step-title">Choose your package</h2>
              <p className="step-sub">Every package is performed by hand at your location.</p>
              <div className="opt-list">
                {PACKAGES.map(p => (
                  <button key={p.id} className={'opt ' + (pkgId === p.id ? 'sel ' + (p.popular ? 'gold' : '') : '')} onClick={() => setPkgId(p.id)}>
                    <span className="opt-ic"><PkgIcon icon={p.icon} /></span>
                    <span className="opt-body">
                      <h4>{p.name}{p.popular && <span className="tagm">POPULAR</span>}</h4>
                      <p>{p.desc} · {p.time}</p>
                    </span>
                    <span className="opt-price"><small>from</small><b>{money(p.price)}</b></span>
                    <span className="opt-check"><Check /></span>
                  </button>
                ))}
              </div>
            </div>
          )}

          {/* STEP 1 — Vehicle + add-ons */}
          {step === 1 && (
            <div>
              <h2 className="step-title">Tell us about your vehicle</h2>
              <p className="step-sub">Pricing adjusts for size — pick the closest match.</p>
              <div className="opt-list">
                {VEHICLES.map(v => (
                  <button key={v.id} className={'opt ' + (vehId === v.id ? 'sel' : '')} onClick={() => setVehId(v.id)}>
                    <span className="opt-ic">
                      <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M3 13l2-6a3 3 0 0 1 2.8-2h8.4A3 3 0 0 1 19 7l2 6v5H3z"/><circle cx="7" cy="18" r="1.6"/><circle cx="17" cy="18" r="1.6"/></svg>
                    </span>
                    <span className="opt-body"><h4>{v.name}</h4><p>{v.desc}</p></span>
                    <span className="opt-price"><b>{v.surcharge === 0 ? 'Base' : '+' + money(v.surcharge)}</b></span>
                    <span className="opt-check"><Check /></span>
                  </button>
                ))}
              </div>

              <div className="field-group">
                <label className="gl">Add-on treatments <span style={{ color: 'var(--muted)', fontWeight: 400, textTransform: 'none', letterSpacing: 0 }}>· optional</span></label>
                <div className="addon-grid2">
                  {ADDONS.map(a => (
                    <button key={a.id} className={'addon-chip ' + (addonIds.includes(a.id) ? 'sel' : '')} onClick={() => toggleAddon(a.id)}>
                      <span className="box"><Check /></span>
                      <span className="ac-body"><b>{a.name}</b><span>{a.note}</span></span>
                      <span className="ac-price">+{money(a.price)}</span>
                    </button>
                  ))}
                </div>
              </div>
            </div>
          )}

          {/* STEP 2 — Date & time */}
          {step === 2 && (
            <div>
              <h2 className="step-title">Pick a date &amp; time</h2>
              <p className="step-sub">We operate Monday–Saturday, 8am to 7pm.</p>
              <div className="cal">
                <Calendar selected={date} onSelect={(d) => { setDate(d); setTime(''); }} />
                <div>
                  <div className="slots-label">{date ? 'Available times' : 'Select a date first'}</div>
                  <div className="slots">
                    {date ? TIME_SLOTS.map(t => (
                      <button key={t} className={'slot ' + (time === t ? 'sel' : '')} onClick={() => setTime(t)}>{t}</button>
                    )) : <div className="slots-empty">Choose a day on the calendar to see open slots.</div>}
                  </div>
                </div>
              </div>
            </div>
          )}

          {/* STEP 3 — Details */}
          {step === 3 && (
            <div>
              <h2 className="step-title">Where should we come?</h2>
              <p className="step-sub">We'll bring everything — just point us to the car.</p>
              <div className="form-grid">
                <div className="fld">
                  <label>Full name</label>
                  <input className={errors.name ? 'err' : ''} value={form.name} onChange={e => setField('name', e.target.value)} placeholder="Jordan Smith" />
                  {errors.name && <span className="err-msg">{errors.name}</span>}
                </div>
                <div className="fld">
                  <label>Phone</label>
                  <input className={errors.phone ? 'err' : ''} value={form.phone} onChange={e => setField('phone', e.target.value)} placeholder="(902) 555-0123" />
                  {errors.phone && <span className="err-msg">{errors.phone}</span>}
                </div>
                <div className="fld full">
                  <label>Email</label>
                  <input className={errors.email ? 'err' : ''} value={form.email} onChange={e => setField('email', e.target.value)} placeholder="you@email.com" />
                  {errors.email && <span className="err-msg">{errors.email}</span>}
                </div>
                <div className="fld full">
                  <label>Address where the car will be</label>
                  <input className={errors.address ? 'err' : ''} value={form.address} onChange={e => setField('address', e.target.value)} placeholder="123 Maple Street" />
                  {errors.address && <span className="err-msg">{errors.address}</span>}
                </div>
                <div className="fld">
                  <label>City</label>
                  <select value={form.city} onChange={e => setField('city', e.target.value)}>
                    {CITIES.map(c => <option key={c}>{c}</option>)}
                  </select>
                </div>
                <div className="fld">
                  <label>Vehicle make &amp; model <span style={{ color: 'var(--muted)' }}>(optional)</span></label>
                  <input value={form.vehicleModel || ''} onChange={e => setField('vehicleModel', e.target.value)} placeholder="e.g. Honda CR-V" />
                </div>
                <div className="fld full">
                  <label>Anything we should know? <span style={{ color: 'var(--muted)' }}>(optional)</span></label>
                  <textarea value={form.notes} onChange={e => setField('notes', e.target.value)} placeholder="Pet hair, spills, parking notes, gate codes…"></textarea>
                </div>
              </div>
            </div>
          )}

          {/* STEP 4 — Review */}
          {step === 4 && (
            <div>
              <h2 className="step-title">Review &amp; confirm</h2>
              <p className="step-sub">Double-check the details, then lock it in.</p>
              <div className="rev-block">
                <div><h5>Package</h5><div className="rb-val"><b>{pkg.name}</b> — {money(pkg.price)} base · {pkg.time}</div></div>
                <button className="rev-edit" onClick={() => setStep(0)}>Edit</button>
              </div>
              <div className="rev-block">
                <div><h5>Vehicle &amp; add-ons</h5><div className="rb-val"><b>{vehicle.name}</b>{vehicle.surcharge > 0 ? ' (+' + money(vehicle.surcharge) + ')' : ''}{addons.length ? ' · ' + addons.map(a => a.name).join(', ') : ' · No add-ons'}</div></div>
                <button className="rev-edit" onClick={() => setStep(1)}>Edit</button>
              </div>
              <div className="rev-block">
                <div><h5>Date &amp; time</h5><div className="rb-val"><b>{fmtDate(date)}</b> at {time}</div></div>
                <button className="rev-edit" onClick={() => setStep(2)}>Edit</button>
              </div>
              <div className="rev-block">
                <div><h5>Contact &amp; location</h5><div className="rb-val"><b>{form.name}</b><br/>{form.address}, {form.city}<br/>{form.phone} · {form.email}</div></div>
                <button className="rev-edit" onClick={() => setStep(3)}>Edit</button>
              </div>
            </div>
          )}

          <div className="step-nav">
            {step > 0 ? (
              <button className="btn-back" onClick={back}>
                <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M19 12H5M11 6l-6 6 6 6"/></svg> Back
              </button>
            ) : <span />}
            {step < 4 ? (
              <button className="btn btn--gold" disabled={!canNext()} onClick={next}>Continue <Arrow /></button>
            ) : (
              <button className="btn btn--gold btn--lg" onClick={next}>Confirm booking <Arrow /></button>
            )}
          </div>
        </div>

        <Summary pkg={pkg} vehicle={vehicle} addons={addons} date={date} time={time} total={total} />
      </div>
    </div>
  );
}

ReactDOM.createRoot(document.getElementById('booking-root')).render(<BookingApp />);
