// booking.jsx — multi-step "Book a fitting" flow. Exports BookingModal to window.
const { useState, useEffect } = React;

const SERVICES = [
  { id: "wedding", name: "Wedding dress",  meta: "Bustles, bodice, hem, sleeves" },
  { id: "suit",    name: "Suit jacket",    meta: "Shoulders, sleeves, side seams" },
  { id: "daily",   name: "Daily wear",     meta: "Hems, tapers, side seams" },
  { id: "other",   name: "Something else", meta: "Tell us what you've got" },
];

const TIMES = ["10:00", "11:30", "13:00", "14:30", "16:00", "17:30"];

// build the next ~14 open days (skip Sundays — shop closed)
function upcomingDays(n) {
  const out = [];
  const d = new Date(2026, 4, 29); // pitch-stable start: Fri May 29 2026
  while (out.length < n) {
    if (d.getDay() !== 0) out.push(new Date(d));
    d.setDate(d.getDate() + 1);
  }
  return out;
}
const DAYS = upcomingDays(12);
const DOW = ["Sun","Mon","Tue","Wed","Thu","Fri","Sat"];
const MON = ["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];

function StepDots({ step }) {
  return (
    <div style={bk.dots}>
      {[0,1,2,3].map(i => (
        <span key={i} style={{ ...bk.dot, ...(i <= step ? bk.dotOn : {}) }} />
      ))}
    </div>
  );
}

function BookingModal({ open, onClose, initialService }) {
  const [step, setStep] = useState(0);
  const [service, setService] = useState(initialService || null);
  const [day, setDay] = useState(null);
  const [time, setTime] = useState(null);
  const [form, setForm] = useState({ name: "", email: "", phone: "", notes: "" });

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

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

  if (!open) return null;

  const svcObj = SERVICES.find(s => s.id === service);
  const canNext = (step === 0 && service) || (step === 1 && day) ||
                  (step === 2 && form.name && form.email);

  const titles = ["What are you bringing in?", "Preferred day", "Your details", "Request received"];

  return (
    <div style={bk.overlay} onMouseDown={onClose}>
      <div style={bk.modal} onMouseDown={e => e.stopPropagation()}>
        <button style={bk.close} onClick={onClose} aria-label="Close">&times;</button>

        <div style={bk.head}>
          <p className="eyebrow" style={{ marginBottom: 10 }}>Book a fitting</p>
          <h3 className="display" style={bk.title}>{titles[step]}</h3>
          {step < 3 && <StepDots step={step} />}
        </div>

        <div style={bk.body}>
          {step === 0 && (
            <div style={bk.svcGrid} data-grid="svc-modal">
              {SERVICES.map(s => {
                const on = service === s.id;
                return (
                  <button key={s.id} onClick={() => setService(s.id)}
                    style={{ ...bk.svcCard, ...(on ? bk.svcCardOn : {}) }}>
                    <span style={bk.svcName}>{s.name}</span>
                    <span style={bk.svcMeta}>{s.meta}</span>
                  </button>
                );
              })}
            </div>
          )}

          {step === 1 && (
            <div>
              <p style={bk.fieldLabel}>Pick a day to come by</p>
              <div style={bk.dayRow}>
                {DAYS.map((d, i) => {
                  const on = day && day.getTime() === d.getTime();
                  return (
                    <button key={i} onClick={() => setDay(d)}
                      style={{ ...bk.dayCell, ...(on ? bk.cellOn : {}) }}>
                      <span style={bk.dayDow}>{DOW[d.getDay()]}</span>
                      <span style={bk.dayNum}>{d.getDate()}</span>
                      <span style={bk.dayMon}>{MON[d.getMonth()]}</span>
                    </button>
                  );
                })}
              </div>
              <p className="faint" style={{ fontSize: "0.84rem", marginTop: 22 }}>
                Bring the garment in and put it on — the tailor will pin it and
                quote you on the spot. No fixed appointment times; we'll confirm by phone.
              </p>
            </div>
          )}

          {step === 2 && (
            <div style={bk.formGrid} data-grid="form">
              <label style={bk.l}><span style={bk.fieldLabel}>Full name</span>
                <input style={bk.input} value={form.name}
                  onChange={e => setForm({ ...form, name: e.target.value })} placeholder="Jane Doe" /></label>
              <label style={bk.l}><span style={bk.fieldLabel}>Email</span>
                <input style={bk.input} value={form.email} type="email"
                  onChange={e => setForm({ ...form, email: e.target.value })} placeholder="jane@email.com" /></label>
              <label style={bk.l}><span style={bk.fieldLabel}>Phone <span style={bk.opt}>(optional)</span></span>
                <input style={bk.input} value={form.phone}
                  onChange={e => setForm({ ...form, phone: e.target.value })} placeholder="Your phone number" /></label>
              <label style={{ ...bk.l, gridColumn: "1 / -1" }}><span style={bk.fieldLabel}>What are you after? <span style={bk.opt}>(optional)</span></span>
                <textarea style={{ ...bk.input, minHeight: 78, resize: "vertical", fontFamily: "var(--body)" }} value={form.notes}
                  onChange={e => setForm({ ...form, notes: e.target.value })} placeholder="A navy three-piece for an autumn wedding…" /></label>
            </div>
          )}

          {step === 3 && (
            <div style={bk.done}>
              <div style={bk.check}>✓</div>
              <p style={bk.doneLead}>
                Thanks, {form.name.split(" ")[0] || "friend"}. Your request is in — we'll
                call to confirm a time.
              </p>
              <div style={bk.receipt}>
                <Row k="Bringing in" v={svcObj ? svcObj.name : "—"} />
                <Row k="Preferred day" v={day ? `${DOW[day.getDay()]} ${MON[day.getMonth()]} ${day.getDate()}` : "—"} />
                <Row k="Where" v="6371 Cambie St, Vancouver, BC" />
                <Row k="We'll confirm via" v={form.email} last />
              </div>
              <p className="faint" style={{ fontSize: "0.84rem", marginTop: 22 }}>
                Prefer to talk it through now? Call the shop on (604) 325-0545.
              </p>
            </div>
          )}
        </div>

        <div style={bk.foot}>
          {step > 0 && step < 3
            ? <button className="btn link-underline" onClick={() => setStep(step - 1)}>← Back</button>
            : <span />}
          {step < 2 && (
            <button className="btn btn-accent" disabled={!canNext}
              style={{ opacity: canNext ? 1 : 0.4, cursor: canNext ? "pointer" : "not-allowed" }}
              onClick={() => setStep(step + 1)}>Continue</button>
          )}
          {step === 2 && (
            <button className="btn btn-accent" disabled={!canNext}
              style={{ opacity: canNext ? 1 : 0.4, cursor: canNext ? "pointer" : "not-allowed" }}
              onClick={() => setStep(3)}>Send request</button>
          )}
          {step === 3 && (
            <button className="btn btn-fill" onClick={onClose}>Done</button>
          )}
        </div>
      </div>
    </div>
  );
}

function Row({ k, v, last }) {
  return (
    <div style={{ ...bk.rRow, borderBottom: last ? "none" : "1px solid var(--line)" }}>
      <span style={bk.rK}>{k}</span>
      <span style={bk.rV}>{v}</span>
    </div>
  );
}

const bk = {
  overlay: { position: "fixed", inset: 0, background: "rgba(20,16,12,0.55)", backdropFilter: "blur(4px)",
    display: "flex", alignItems: "center", justifyContent: "center", padding: 20, zIndex: 1000, animation: "bkFade .25s ease" },
  modal: { background: "var(--paper)", width: "min(640px, 100%)", maxHeight: "92vh", overflowY: "auto",
    borderRadius: 4, position: "relative", boxShadow: "0 40px 120px rgba(20,16,12,0.4)", animation: "bkRise .35s cubic-bezier(.2,.7,.2,1)" },
  close: { position: "absolute", top: 18, right: 20, background: "none", border: "none", fontSize: 28, lineHeight: 1,
    color: "var(--ink-soft)", cursor: "pointer", zIndex: 2 },
  head: { padding: "38px 44px 22px", borderBottom: "1px solid var(--line)" },
  title: { fontSize: "2.2rem" },
  dots: { display: "flex", gap: 7, marginTop: 18 },
  dot: { width: 26, height: 3, borderRadius: 2, background: "var(--line)", transition: "background .3s" },
  dotOn: { background: "var(--accent)" },
  body: { padding: "30px 44px" },
  foot: { display: "flex", justifyContent: "space-between", alignItems: "center", padding: "20px 44px 34px" },

  svcGrid: { display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12 },
  svcCard: { display: "flex", flexDirection: "column", alignItems: "flex-start", gap: 4, textAlign: "left",
    padding: "20px 22px", background: "var(--paper-2)", border: "1px solid var(--line)", borderRadius: 3, cursor: "pointer",
    transition: "border-color .25s, background .25s, transform .25s" },
  svcCardOn: { borderColor: "var(--accent)", background: "var(--paper)", transform: "translateY(-2px)", boxShadow: "0 8px 24px rgba(20,16,12,0.08)" },
  svcName: { fontFamily: "var(--display)", fontSize: "1.5rem", fontWeight: 500, lineHeight: 1.1 },
  svcMeta: { fontSize: "0.84rem", color: "var(--ink-soft)" },
  svcDur: { fontSize: "0.7rem", letterSpacing: "0.08em", textTransform: "uppercase", color: "var(--accent)", marginTop: 6, fontWeight: 600 },

  fieldLabel: { fontSize: "0.72rem", fontWeight: 600, letterSpacing: "0.12em", textTransform: "uppercase", color: "var(--ink-soft)", margin: "0 0 12px" },
  opt: { color: "var(--ink-faint)", fontWeight: 400, letterSpacing: 0, textTransform: "none" },
  dayRow: { display: "grid", gridTemplateColumns: "repeat(6, 1fr)", gap: 8 },
  dayCell: { display: "flex", flexDirection: "column", alignItems: "center", gap: 2, padding: "12px 4px",
    background: "var(--paper-2)", border: "1px solid var(--line)", borderRadius: 3, cursor: "pointer", transition: "all .2s" },
  dayDow: { fontSize: "0.62rem", letterSpacing: "0.08em", textTransform: "uppercase", color: "var(--ink-faint)" },
  dayNum: { fontFamily: "var(--display)", fontSize: "1.5rem", fontWeight: 500, lineHeight: 1 },
  dayMon: { fontSize: "0.62rem", letterSpacing: "0.06em", textTransform: "uppercase", color: "var(--ink-faint)" },
  timeRow: { display: "grid", gridTemplateColumns: "repeat(6, 1fr)", gap: 8 },
  timeCell: { padding: "13px 4px", background: "var(--paper-2)", border: "1px solid var(--line)", borderRadius: 3,
    cursor: "pointer", fontFamily: "var(--body)", fontSize: "0.92rem", fontWeight: 500, transition: "all .2s" },
  cellOn: { background: "var(--ink)", color: "var(--paper)", borderColor: "var(--ink)" },

  formGrid: { display: "grid", gridTemplateColumns: "1fr 1fr", gap: 18 },
  l: { display: "flex", flexDirection: "column" },
  input: { padding: "12px 14px", border: "1px solid var(--line)", borderRadius: 3, background: "var(--paper-2)",
    fontSize: "0.95rem", color: "var(--ink)", outline: "none", fontFamily: "var(--body)" },

  done: { textAlign: "center", paddingTop: 6 },
  check: { width: 58, height: 58, borderRadius: "50%", background: "var(--accent)", color: "var(--paper)",
    display: "flex", alignItems: "center", justifyContent: "center", fontSize: 28, margin: "0 auto 22px" },
  doneLead: { fontFamily: "var(--display)", fontSize: "1.5rem", fontWeight: 500, lineHeight: 1.3, margin: "0 auto 26px", maxWidth: 420 },
  receipt: { textAlign: "left", border: "1px solid var(--line)", borderRadius: 4, padding: "4px 20px", maxWidth: 440, margin: "0 auto", background: "var(--paper-2)" },
  rRow: { display: "flex", justifyContent: "space-between", gap: 16, padding: "13px 0" },
  rK: { fontSize: "0.72rem", letterSpacing: "0.1em", textTransform: "uppercase", color: "var(--ink-faint)", fontWeight: 600 },
  rV: { fontSize: "0.92rem", fontWeight: 500, textAlign: "right" },
};

window.BookingModal = BookingModal;
