/* Multi-step booking flow modal. Exports window.BookingModal.
   Steps: Service → Time → Details → Done. No named barbers (per brief). */
const { useState, useEffect, useMemo, useRef } = React;

const DAYS = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
const MONTHS = ["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];

function nextDays(n) {
  const out = [];
  const d = new Date();
  for (let i = 0; i < n; i++) {
    const x = new Date(d);
    x.setDate(d.getDate() + i);
    out.push(x);
  }
  return out;
}

function slotsFor(date) {
  const day = date.getDay();
  const start = 9, end = day === 0 ? 16 : day === 6 ? 18 : 19;
  const out = [];
  for (let h = start; h < end; h++) out.push(`${h}:00`, `${h}:30`);
  const seed = date.getDate();
  return out.map((t, i) => ({ t, taken: (i * 7 + seed) % 5 === 0 }));
}

const STEP_LABELS = ["Service", "Time", "Details", "Done"];

function BookingModal({ open, onClose, initialService }) {
  const [step, setStep] = useState(0);
  const [service, setService] = useState(null);
  const [date, setDate] = useState(null);
  const [time, setTime] = useState(null);
  const [form, setForm] = useState({ name: "", phone: "", email: "", notes: "" });
  const [touched, setTouched] = useState(false);
  const days = useMemo(() => nextDays(14), []);
  const scrollRef = useRef(null);

  useEffect(() => {
    if (open) {
      setStep(initialService ? 1 : 0);
      setService(initialService || null);
      setDate(null); setTime(null);
      setForm({ name: "", phone: "", email: "", notes: "" });
      setTouched(false);
    }
  }, [open, initialService]);

  useEffect(() => {
    function onKey(e) { if (e.key === "Escape") onClose(); }
    if (open) window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, [open, onClose]);

  useEffect(() => { if (scrollRef.current) scrollRef.current.scrollTop = 0; }, [step]);

  if (!open) return null;

  const emailOk = /^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(form.email);
  const phoneOk = form.phone.replace(/\D/g, "").length >= 10;
  const detailsOk = form.name.trim().length > 1 && (emailOk || phoneOk);

  const canNext =
    (step === 0 && service) ||
    (step === 1 && date && time) ||
    (step === 2 && detailsOk);

  function next() {
    if (step === 2) { setStep(3); return; }
    if (canNext) setStep((s) => Math.min(s + 1, 3));
  }
  function back() { setStep((s) => Math.max(s - 1, 0)); }

  return (
    <div className="bk-overlay" onMouseDown={(e) => { if (e.target === e.currentTarget) onClose(); }}>
      <div className="bk-modal" role="dialog" aria-modal="true" aria-label="Book a chair">
        <button className="bk-x" onClick={onClose} aria-label="Close">✕</button>

        <div className="bk-steps">
          {STEP_LABELS.map((l, i) => (
            <div key={l} className={"bk-step" + (i === step ? " active" : "") + (i < step ? " done" : "")}>
              <span className="bk-step-dot">{i < step ? "✓" : i + 1}</span>
              <span className="bk-step-label cond">{l}</span>
            </div>
          ))}
        </div>

        <div className="bk-body" ref={scrollRef}>
          {step === 0 && (
            <div className="bk-pane">
              <h3 className="serif bk-h">Pick your service</h3>
              <div className="bk-services">
                {CUTS.map((s) => (
                  <button key={s.id}
                    className={"bk-svc" + (service?.id === s.id ? " sel" : "")}
                    onClick={() => setService(s)}>
                    <div className="bk-svc-top">
                      <span className="serif bk-svc-name">{s.name}</span>
                      <span className="bk-svc-price cond">From ${s.price}</span>
                    </div>
                    <div className="bk-svc-desc">{s.desc}</div>
                    <div className="bk-svc-mins">{s.mins} min</div>
                  </button>
                ))}
              </div>
            </div>
          )}

          {step === 1 && (
            <div className="bk-pane">
              <h3 className="serif bk-h">When works for you?</h3>
              <div className="bk-dayrow">
                {days.map((d) => {
                  const sel = date && d.toDateString() === date.toDateString();
                  return (
                    <button key={d.toISOString()} className={"bk-day" + (sel ? " sel" : "")}
                      onClick={() => { setDate(d); setTime(null); }}>
                      <span className="bk-day-dow cond">{DAYS[d.getDay()]}</span>
                      <span className="serif bk-day-num">{d.getDate()}</span>
                      <span className="bk-day-mon cond">{MONTHS[d.getMonth()]}</span>
                    </button>
                  );
                })}
              </div>
              {date ? (
                <div className="bk-slots">
                  {slotsFor(date).map((s) => (
                    <button key={s.t} disabled={s.taken}
                      className={"bk-slot" + (time === s.t ? " sel" : "") + (s.taken ? " taken" : "")}
                      onClick={() => setTime(s.t)}>{s.t}</button>
                  ))}
                </div>
              ) : <p className="bk-hint">Select a day to see open chairs.</p>}
            </div>
          )}

          {step === 2 && (
            <div className="bk-pane">
              <h3 className="serif bk-h">Your details</h3>
              <div className="bk-form">
                <label className="bk-field">
                  <span className="cond">Name</span>
                  <input value={form.name} onChange={(e) => setForm({ ...form, name: e.target.value })}
                    onBlur={() => setTouched(true)} placeholder="First and last" />
                </label>
                <div className="bk-field-row">
                  <label className="bk-field">
                    <span className="cond">Phone</span>
                    <input value={form.phone} onChange={(e) => setForm({ ...form, phone: e.target.value })}
                      onBlur={() => setTouched(true)} placeholder="(604) 620-7811" inputMode="tel" />
                  </label>
                  <label className="bk-field">
                    <span className="cond">Email</span>
                    <input value={form.email} onChange={(e) => setForm({ ...form, email: e.target.value })}
                      onBlur={() => setTouched(true)} placeholder="you@email.com" inputMode="email" />
                  </label>
                </div>
                <label className="bk-field">
                  <span className="cond">Notes <em>(optional)</em></span>
                  <textarea value={form.notes} onChange={(e) => setForm({ ...form, notes: e.target.value })}
                    placeholder="Anything your barber should know" rows="2"></textarea>
                </label>
                {touched && !detailsOk && (
                  <p className="bk-err">Add your name and at least a phone or email so we can confirm.</p>
                )}
              </div>
            </div>
          )}

          {step === 3 && (
            <div className="bk-pane bk-confirm">
              <div className="bk-check">✓</div>
              <h3 className="serif bk-h">You're booked{form.name.trim() ? `, ${form.name.split(" ")[0]}` : ""}.</h3>
              <p className="bk-confirm-sub">A confirmation is on its way. See you on Broadway.</p>
              <div className="bk-summary">
                <Row k="Service" v={`${service?.name} · from $${service?.price}`} />
                <Row k="When" v={date ? `${DAYS[date.getDay()]} ${MONTHS[date.getMonth()]} ${date.getDate()}, ${time}` : ""} />
                <Row k="Where" v={`${SHOP.street}, ${SHOP.cityShort}`} />
              </div>
            </div>
          )}
        </div>

        {step < 3 ? (
          <div className="bk-foot">
            <button className="bk-back cond" onClick={back} disabled={step === 0} style={{ opacity: step === 0 ? 0.35 : 1 }}>← Back</button>
            <div className="bk-foot-right">
              {service && <span className="bk-runtotal">{service.name} · from ${service.price}</span>}
              <button className={"btn btn-primary" + (canNext ? "" : " is-off")} onClick={next} disabled={!canNext}>
                {step === 2 ? "Confirm booking" : "Continue"}
              </button>
            </div>
          </div>
        ) : (
          <div className="bk-foot">
            <span className="bk-runtotal">Booksy is easiest — but the door's open.</span>
            <button className="btn btn-primary" onClick={onClose}>Done</button>
          </div>
        )}
      </div>
    </div>
  );
}

function Row({ k, v }) {
  return (
    <div className="bk-srow">
      <span className="bk-srow-k cond">{k}</span>
      <span className="bk-srow-v">{v}</span>
    </div>
  );
}

window.BookingModal = BookingModal;
