// Precision Mobile Car Care — booking modal

const { useState: useStateB, useEffect: useEffectB } = React;

function BookingModal({ onClose }) {
  const [step, setStep] = useStateB(0);
  const [vehicleType, setVehicleType] = useStateB(null);
  const [services, setServices] = useStateB([]);
  const [schedule, setSchedule] = useStateB({ date: "", time: "" });
  const [contact, setContact] = useStateB({ name: "", phone: "", email: "", suburb: "", vehicle: "", notes: "" });
  const [errors, setErrors] = useStateB({});
  const [sending, setSending] = useStateB(false);

  useEffectB(() => {
    const fn = (e) => { if (e.key === "Escape") onClose(); };
    window.addEventListener("keydown", fn);
    document.body.style.overflow = "hidden";
    return () => {
      window.removeEventListener("keydown", fn);
      document.body.style.overflow = "";
    };
  }, [onClose]);

  const STEPS = ["Vehicle", "Services", "Preferred date", "Details", "Review"];

  const toggleService = (id) => {
    setServices(prev => prev.includes(id) ? prev.filter(x => x !== id) : [...prev, id]);
  };

  const validateContact = () => {
    const e = {};
    if (!contact.name.trim()) e.name = "Required";
    if (!contact.phone.trim() || contact.phone.replace(/\D/g, "").length < 8) e.phone = "Valid phone required";
    if (contact.email && !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(contact.email)) e.email = "Invalid email";
    if (!contact.suburb.trim()) e.suburb = "Required";
    if (!contact.vehicle.trim()) e.vehicle = "Required";
    setErrors(e);
    return Object.keys(e).length === 0;
  };

  // Pure, side-effect-free validity check for the "Continue" disabled state.
  // (validateContact() calls setErrors() — calling it during render caused an
  // infinite re-render loop, so the Details step must use this instead.)
  const isContactValid = () => {
    if (!contact.name.trim()) return false;
    if (!contact.phone.trim() || contact.phone.replace(/\D/g, "").length < 8) return false;
    if (contact.email && !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(contact.email)) return false;
    if (!contact.suburb.trim()) return false;
    if (!contact.vehicle.trim()) return false;
    return true;
  };

  const canAdvance = () => {
    if (step === 0) return !!vehicleType;
    if (step === 1) return services.length > 0;
    if (step === 2) return !!schedule.date && !!schedule.time;
    if (step === 3) return isContactValid();
    return true;
  };

  const advance = () => {
    if (step === 3) {
      if (!validateContact()) return;
    }
    if (step < STEPS.length - 1) setStep(step + 1);
  };

  const renderStep = () => {
    if (step === 0) {
      return (
        <>
          <div className="eyebrow" style={{marginBottom: 18}}><span className="dot"></span>Step 1 — What are we detailing?</div>
          <div className="choice-grid">
            {VEHICLES.map(v => (
              <button
                key={v.id}
                className={`choice ${vehicleType === v.id ? "selected" : ""}`}
                onClick={() => setVehicleType(v.id)}
              >
                <div className="c-icon">{v.code}</div>
                <div className="c-text">
                  <div className="c-title">{v.title}</div>
                </div>
              </button>
            ))}
          </div>
        </>
      );
    }
    if (step === 1) {
      return (
        <>
          <div className="eyebrow" style={{marginBottom: 18}}><span className="dot"></span>Step 2 — Choose your services <span style={{color: "var(--fg-2)", marginLeft: 8, textTransform: "none", letterSpacing: 0}}>(pick one or more)</span></div>
          <div className="service-pick-list">
            {SERVICES.map(s => (
              <button
                key={s.id}
                className={`svc-pick ${services.includes(s.id) ? "selected" : ""}`}
                onClick={() => toggleService(s.id)}
              >
                <div className="chk">{services.includes(s.id) && "✓"}</div>
                <div style={{flex: 1, display: "flex", justifyContent: "space-between", alignItems: "center", gap: 14}}>
                  <div className="name">{s.name}</div>
                  <div className="mono" style={{color: "var(--muted)"}}>{s.category === "mobile" ? "Mobile" : "Specialty"}</div>
                </div>
              </button>
            ))}
          </div>
        </>
      );
    }
    if (step === 2) {
      const today = new Date().toISOString().split("T")[0];
      const times = ["Morning (7am–12pm)", "Afternoon (12pm–5pm)", "Flexible"];
      return (
        <>
          <div className="eyebrow" style={{marginBottom: 18}}><span className="dot"></span>Step 3 — When suits you?</div>
          <div className="field-row">
            <div className="field">
              <label>Preferred date</label>
              <input type="date" value={schedule.date} min={today} onChange={e => setSchedule({...schedule, date: e.target.value})}/>
            </div>
            <div className="field">
              <label>Preferred time</label>
              <select value={schedule.time} onChange={e => setSchedule({...schedule, time: e.target.value})}>
                <option value="">Pick a time</option>
                {times.map(t => <option key={t} value={t}>{t}</option>)}
              </select>
            </div>
          </div>
          <div style={{padding: 18, background: "var(--bg)", border: "1px solid var(--line)", borderRadius: 4, fontSize: 14, color: "var(--fg-2)"}}>
            This is a request — we'll confirm an exact day and time when we get back to you with the quote.
          </div>
        </>
      );
    }
    if (step === 3) {
      return (
        <>
          <div className="eyebrow" style={{marginBottom: 18}}><span className="dot"></span>Step 4 — Your details</div>
          <div className="field-row">
            <div className={`field ${errors.name ? "error" : ""}`}>
              <label>Your name *</label>
              <input value={contact.name} onChange={e => setContact({...contact, name: e.target.value})} placeholder="First and last"/>
              {errors.name && <div className="err">{errors.name}</div>}
            </div>
            <div className={`field ${errors.phone ? "error" : ""}`}>
              <label>Mobile *</label>
              <input value={contact.phone} onChange={e => setContact({...contact, phone: e.target.value})} placeholder="04..."/>
              {errors.phone && <div className="err">{errors.phone}</div>}
            </div>
          </div>
          <div className="field-row">
            <div className={`field ${errors.email ? "error" : ""}`}>
              <label>Email (optional)</label>
              <input value={contact.email} onChange={e => setContact({...contact, email: e.target.value})} placeholder="you@..."/>
              {errors.email && <div className="err">{errors.email}</div>}
            </div>
            <div className={`field ${errors.suburb ? "error" : ""}`}>
              <label>Suburb / address *</label>
              <input value={contact.suburb} onChange={e => setContact({...contact, suburb: e.target.value})} placeholder="Where the car lives"/>
              {errors.suburb && <div className="err">{errors.suburb}</div>}
            </div>
          </div>
          <div className={`field ${errors.vehicle ? "error" : ""}`}>
            <label>Vehicle (year, make, model, colour) *</label>
            <input value={contact.vehicle} onChange={e => setContact({...contact, vehicle: e.target.value})} placeholder="e.g. 1971 Ford XY GT — Vermilion Fire"/>
            {errors.vehicle && <div className="err">{errors.vehicle}</div>}
          </div>
          <div className="field">
            <label>Notes</label>
            <textarea rows="3" value={contact.notes} onChange={e => setContact({...contact, notes: e.target.value})} placeholder="Anything we should know? Existing defects, garage access, deadlines..." />
          </div>
        </>
      );
    }
    if (step === 4) {
      const v = VEHICLES.find(x => x.id === vehicleType);
      const svcNames = services.map(id => SERVICES.find(s => s.id === id)?.name).filter(Boolean).join(", ");
      return (
        <>
          <div className="eyebrow" style={{marginBottom: 18}}><span className="dot"></span>Review your request</div>
          <div className="summary">
            <div className="sum-row"><div className="k">Vehicle type</div><div>{v?.title}</div></div>
            <div className="sum-row"><div className="k">Services</div><div>{svcNames}</div></div>
            <div className="sum-row"><div className="k">When</div><div>{schedule.date}{schedule.time ? ` · ${schedule.time}` : ""}</div></div>
            <div className="sum-row"><div className="k">Name</div><div>{contact.name}</div></div>
            <div className="sum-row"><div className="k">Phone</div><div>{contact.phone}</div></div>
            {contact.email && <div className="sum-row"><div className="k">Email</div><div>{contact.email}</div></div>}
            <div className="sum-row"><div className="k">Suburb</div><div>{contact.suburb}</div></div>
            <div className="sum-row"><div className="k">Vehicle</div><div>{contact.vehicle}</div></div>
            {contact.notes && <div className="sum-row"><div className="k">Notes</div><div>{contact.notes}</div></div>}
          </div>
          <div style={{marginTop: 18, padding: 16, background: "color-mix(in oklch, var(--accent) 10%, transparent)", border: "1px solid color-mix(in oklch, var(--accent) 40%, transparent)", borderRadius: 4, fontSize: 13, color: "var(--fg)"}}>
            <strong style={{fontFamily: "var(--mono)", fontSize: 10, letterSpacing: "0.18em", textTransform: "uppercase", display: "block", marginBottom: 6}}>What happens next</strong>
            We'll call you on {contact.phone || "your mobile"} to confirm details and give you a quote. No payment required.
          </div>
        </>
      );
    }
    return null;
  };

  return (
    <div className="modal-backdrop" onClick={e => e.target === e.currentTarget && onClose()}>
      <div className="modal">
        <div className="modal-head">
          <div className="title">Get a Quote</div>
          <button className="close" onClick={onClose} aria-label="Close">✕</button>
        </div>

        <div className="modal-body">
          {step < 5 && (
            <div className="steps">
              {STEPS.map((_, i) => (
                <div key={i} className={`step-bar ${i < step ? "done" : i === step ? "active" : ""}`}></div>
              ))}
            </div>
          )}
          {renderStep()}
        </div>

        <div className="modal-foot">
          <button className="btn btn-ghost" onClick={step === 0 ? onClose : () => setStep(step - 1)}>
            {step === 0 ? "Cancel" : "← Back"}
          </button>
          <div className="mono" style={{color: "var(--muted)"}}>Step {step + 1} / {STEPS.length}</div>
          {step < STEPS.length - 1 ? (
            <button className="btn btn-primary" disabled={!canAdvance()} onClick={advance} style={{opacity: canAdvance() ? 1 : 0.4}}>
              Continue <span className="arrow">→</span>
            </button>
          ) : (
            <button className="btn btn-primary" disabled={sending} onClick={async () => {
              setSending(true);
              await submitBooking({ vehicleType, services, schedule, contact });
              setSending(false);
              setStep(5);
            }}>
              {sending ? "Sending…" : <>Send request <span className="arrow">✓</span></>}
            </button>
          )}
        </div>

        {step === 5 && (
          <div style={{position: "absolute", inset: 0, background: "var(--bg-1)", display: "grid", placeItems: "center", padding: 28}}>
            <div className="success">
              <div className="check">✓</div>
              <h3>Request received</h3>
              <p>Thanks {contact.name.split(" ")[0]}. We'll get back to you on {contact.phone} with a quote.</p>
              <div style={{marginTop: 32, display: "flex", justifyContent: "center"}}><PlateBadge size="lg"/></div>
              <button className="btn btn-ghost" style={{marginTop: 32}} onClick={onClose}>Close</button>
            </div>
          </div>
        )}
      </div>
    </div>
  );
}

Object.assign(window, { BookingModal });
