// booking.jsx — interactive multi-step booking modal
const { useState: useBState, useEffect: useBEffect, useMemo } = React;

const SIZES = [
  { id: "s", label: "Small", sub: "up to 10kg", mult: 0 },
  { id: "m", label: "Medium", sub: "10–22kg", mult: 15 },
  { id: "l", label: "Large", sub: "22–40kg", mult: 35 },
  { id: "xl", label: "X-Large", sub: "40kg+", mult: 55 },
];
const COATS = ["Short / smooth", "Curly / doodle", "Double coat", "Wire / terrier", "Long / silky", "Not sure"];
const TIMES = ["9:00", "10:30", "12:00", "1:30", "3:00", "4:30"];

function buildDays() {
  const out = [];
  const d = new Date(2026, 4, 28); // anchor
  for (let i = 1; i <= 14; i++) {
    const x = new Date(d); x.setDate(d.getDate() + i);
    const dow = x.getDay();
    out.push({
      key: x.toISOString().slice(0, 10),
      dow: ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"][dow],
      day: x.getDate(),
      mon: ["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"][x.getMonth()],
      closed: dow === 1,
    });
  }
  return out;
}

function Field({ label, children, error }) {
  return (
    <label style={{ display: "block" }}>
      <span style={{ display: "block", fontSize: 13, fontWeight: 600, marginBottom: 7, color: "var(--ink)" }}>{label}</span>
      {children}
      {error && <span style={{ display: "block", fontSize: 12.5, color: "var(--accent-ink)", marginTop: 5 }}>{error}</span>}
    </label>
  );
}
const inputStyle = {
  width: "100%", padding: "12px 14px", fontSize: 15, fontFamily: "inherit",
  border: "1.5px solid var(--line)", borderRadius: 12, background: "var(--paper)", color: "var(--ink)", outline: "none",
};

function BookingModal({ open, onClose, initialService }) {
  const [step, setStep] = useBState(0);
  const [done, setDone] = useBState(false);
  const days = useMemo(buildDays, []);
  const [form, setForm] = useBState({
    service: initialService || "full", size: "m", dogName: "", coat: "", notes: "",
    date: "", time: "", ownerName: "", phone: "", email: "", pickup: false,
  });
  const set = (k, v) => setForm(f => ({ ...f, [k]: v }));
  const [errors, setErrors] = useBState({});

  useBEffect(() => { if (open) { setStep(0); setDone(false); setErrors({}); if (initialService) set("service", initialService); } }, [open, initialService]);
  useBEffect(() => {
    document.body.style.overflow = open ? "hidden" : "";
    const esc = (e) => e.key === "Escape" && onClose();
    if (open) window.addEventListener("keydown", esc);
    return () => window.removeEventListener("keydown", esc);
  }, [open]);

  if (!open) return null;

  const svc = SERVICES.find(s => s.id === form.service) || SERVICES[0];
  const size = SIZES.find(s => s.id === form.size);
  const pickupFee = 0;
  const total = svc.price + (size ? size.mult : 0) + pickupFee;

  const steps = ["Service", "Your dog", "Date & time", "Details"];

  function validate(s) {
    const e = {};
    if (s === 1) { if (!form.dogName.trim()) e.dogName = "What's your dog's name?"; if (!form.coat) e.coat = "Pick a coat type"; }
    if (s === 2) { if (!form.date) e.date = "Choose a day"; if (!form.time) e.time = "Choose a time"; }
    if (s === 3) {
      if (!form.ownerName.trim()) e.ownerName = "Your name, please";
      if (!/^[\d\s()+-]{10,}$/.test(form.phone)) e.phone = "A valid phone number, please";
      if (!/^\S+@\S+\.\S+$/.test(form.email)) e.email = "A valid email, please";
    }
    setErrors(e);
    return Object.keys(e).length === 0;
  }
  function next() { if (validate(step)) { if (step === 3) setDone(true); else setStep(s => s + 1); } }
  function back() { setStep(s => Math.max(0, s - 1)); }

  return (
    <div onClick={onClose} style={{
      position: "fixed", inset: 0, zIndex: 100, display: "flex", alignItems: "center", justifyContent: "center",
      background: "color-mix(in srgb, var(--ink) 52%, transparent)", backdropFilter: "blur(5px)", padding: 20,
      animation: "ovIn .25s ease",
    }}>
      <div onClick={e => e.stopPropagation()} style={{
        width: "min(760px, 100%)", maxHeight: "92vh", background: "var(--bg)", borderRadius: 22,
        boxShadow: "0 40px 100px -30px rgba(0,0,0,0.5)", overflow: "hidden", display: "flex", flexDirection: "column",
        animation: "modalIn .3s cubic-bezier(.2,.8,.2,1)",
      }}>
        {/* header */}
        <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", padding: "20px 26px", borderBottom: "1px solid var(--line)" }}>
          <div style={{ display: "flex", alignItems: "center", gap: 11 }}>
            <span style={{ width: 34, height: 34, borderRadius: 10, background: "var(--accent)", color: "#fff", display: "grid", placeItems: "center" }}>{Icon.paw({ ...iconProps, width: 19, height: 19, stroke: "#fff" })}</span>
            <span style={{ fontFamily: "var(--font-display)", fontSize: 18, fontWeight: 700 }}>{done ? "You're booked!" : "Book a spot"}</span>
          </div>
          <button onClick={onClose} aria-label="Close" style={{ width: 34, height: 34, borderRadius: 999, border: "1px solid var(--line)", background: "var(--paper)", color: "var(--ink-soft)", fontSize: 18, lineHeight: 1, display: "grid", placeItems: "center" }}>×</button>
        </div>

        {/* progress */}
        {!done && (
          <div style={{ display: "flex", gap: 8, padding: "16px 26px 0" }}>
            {steps.map((s, i) => (
              <div key={s} style={{ flex: 1 }}>
                <div style={{ height: 4, borderRadius: 99, background: i <= step ? "var(--accent)" : "var(--line)", transition: "background .3s" }} />
                <span style={{ fontSize: 11.5, fontWeight: 600, color: i <= step ? "var(--accent-ink)" : "var(--ink-soft)", marginTop: 6, display: "block" }}>{s}</span>
              </div>
            ))}
          </div>
        )}

        {/* body */}
        <div style={{ padding: "24px 26px", overflowY: "auto", flexGrow: 1 }}>
          {done ? <Confirmation form={form} svc={svc} size={size} total={total} days={days} /> : (
            <>
              {step === 0 && (
                <div>
                  <h3 style={{ fontSize: 22, marginBottom: 4 }}>Which service?</h3>
                  <p style={{ fontSize: 14, color: "var(--ink-soft)", marginBottom: 18 }}>Pick the service you'd like — we'll confirm the exact price for your dog's coat and size.</p>
                  <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12 }} className="bk-svc">
                    {SERVICES.map(s => {
                      const on = form.service === s.id;
                      return (
                        <button key={s.id} onClick={() => set("service", s.id)} style={{
                          textAlign: "left", padding: "16px 16px", borderRadius: 14, background: on ? "var(--card)" : "var(--paper)",
                          border: `1.5px solid ${on ? "var(--accent)" : "var(--line)"}`, display: "flex", gap: 13, alignItems: "flex-start", transition: "border-color .2s, background .2s",
                        }}>
                          <span style={{ color: "var(--accent)", flexShrink: 0, marginTop: 2 }}>{Icon[s.icon]({ ...iconProps, width: 22, height: 22 })}</span>
                          <span>
                            <span style={{ display: "flex", alignItems: "baseline", gap: 8 }}>
                              <span style={{ fontWeight: 700, fontSize: 15 }}>{s.name}</span>
                            </span>
                            <span style={{ display: "block", fontSize: 12.5, color: "var(--ink-soft)", marginTop: 3, lineHeight: 1.4 }}>from ${s.price} · {s.dur}</span>
                          </span>
                        </button>
                      );
                    })}
                  </div>
                </div>
              )}

              {step === 1 && (
                <div style={{ display: "grid", gap: 18 }}>
                  <h3 style={{ fontSize: 22 }}>Tell us about your dog</h3>
                  <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 14 }} className="bk-two">
                    <Field label="Dog's name" error={errors.dogName}>
                      <input style={inputStyle} value={form.dogName} onChange={e => set("dogName", e.target.value)} placeholder="e.g. Biscuit" />
                    </Field>
                    <Field label="Coat type" error={errors.coat}>
                      <select style={inputStyle} value={form.coat} onChange={e => set("coat", e.target.value)}>
                        <option value="">Select…</option>
                        {COATS.map(c => <option key={c} value={c}>{c}</option>)}
                      </select>
                    </Field>
                  </div>
                  <Field label="Size">
                    <div style={{ display: "grid", gridTemplateColumns: "repeat(4,1fr)", gap: 10 }} className="bk-size">
                      {SIZES.map(s => {
                        const on = form.size === s.id;
                        return (
                          <button key={s.id} onClick={() => set("size", s.id)} style={{
                            padding: "12px 8px", borderRadius: 12, background: on ? "var(--card)" : "var(--paper)",
                            border: `1.5px solid ${on ? "var(--accent)" : "var(--line)"}`, textAlign: "center", transition: "border-color .2s, background .2s",
                          }}>
                            <span style={{ display: "block", fontWeight: 700, fontSize: 14 }}>{s.label}</span>
                            <span style={{ display: "block", fontSize: 11.5, color: "var(--ink-soft)", marginTop: 2 }}>{s.sub}</span>
                          </button>
                        );
                      })}
                    </div>
                  </Field>
                  <Field label="Anything we should know? (optional)">
                    <textarea style={{ ...inputStyle, minHeight: 72, resize: "vertical" }} value={form.notes} onChange={e => set("notes", e.target.value)} placeholder="Sensitive spots, anxieties, matting, last groom date…" />
                  </Field>
                </div>
              )}

              {step === 2 && (
                <div>
                  <h3 style={{ fontSize: 22, marginBottom: 14 }}>Pick a day</h3>
                  {errors.date && <p style={{ fontSize: 12.5, color: "var(--accent-ink)", marginBottom: 10 }}>{errors.date}</p>}
                  <div style={{ display: "grid", gridTemplateColumns: "repeat(7,1fr)", gap: 8 }} className="bk-days">
                    {days.map(d => {
                      const on = form.date === d.key;
                      return (
                        <button key={d.key} disabled={d.closed} onClick={() => set("date", d.key)} style={{
                          padding: "10px 4px", borderRadius: 12, textAlign: "center", opacity: d.closed ? 0.32 : 1, cursor: d.closed ? "not-allowed" : "pointer",
                          background: on ? "var(--accent)" : "var(--paper)", color: on ? "#fff" : "var(--ink)",
                          border: `1.5px solid ${on ? "var(--accent)" : "var(--line)"}`, transition: "all .18s",
                        }}>
                          <span style={{ display: "block", fontSize: 11, opacity: 0.75 }}>{d.dow}</span>
                          <span style={{ display: "block", fontSize: 17, fontWeight: 700, fontFamily: "var(--font-display)" }}>{d.day}</span>
                          <span style={{ display: "block", fontSize: 10, opacity: 0.7 }}>{d.mon}</span>
                        </button>
                      );
                    })}
                  </div>
                  <h3 style={{ fontSize: 18, margin: "24px 0 12px" }}>Available times</h3>
                  {errors.time && <p style={{ fontSize: 12.5, color: "var(--accent-ink)", marginBottom: 10 }}>{errors.time}</p>}
                  <div style={{ display: "flex", flexWrap: "wrap", gap: 9 }}>
                    {TIMES.map((t, i) => {
                      const on = form.time === t;
                      const gone = i === 1 || i === 4; // a couple "taken"
                      return (
                        <button key={t} disabled={gone} onClick={() => set("time", t)} style={{
                          padding: "11px 20px", borderRadius: 999, fontWeight: 600, fontSize: 14.5,
                          background: on ? "var(--accent)" : "var(--paper)", color: on ? "#fff" : gone ? "var(--ink-soft)" : "var(--ink)",
                          border: `1.5px solid ${on ? "var(--accent)" : "var(--line)"}`, opacity: gone ? 0.4 : 1, cursor: gone ? "not-allowed" : "pointer",
                          textDecoration: gone ? "line-through" : "none", transition: "all .18s",
                        }}>{t}</button>
                      );
                    })}
                  </div>
                </div>
              )}

              {step === 3 && (
                <div style={{ display: "grid", gap: 16 }}>
                  <h3 style={{ fontSize: 22 }}>Your details</h3>
                  <Field label="Your name" error={errors.ownerName}>
                    <input style={inputStyle} value={form.ownerName} onChange={e => set("ownerName", e.target.value)} placeholder="First & last" />
                  </Field>
                  <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 14 }} className="bk-two">
                    <Field label="Mobile (for text confirmation)" error={errors.phone}>
                      <input style={inputStyle} value={form.phone} onChange={e => set("phone", e.target.value)} placeholder="(604) 555-1234" />
                    </Field>
                    <Field label="Email" error={errors.email}>
                      <input style={inputStyle} value={form.email} onChange={e => set("email", e.target.value)} placeholder="you@email.com" />
                    </Field>
                  </div>
                  <SummaryRow svc={svc} size={size} form={form} days={days} total={total} pickupFee={pickupFee} />
                </div>
              )}
            </>
          )}
        </div>

        {/* footer */}
        {!done && (
          <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", padding: "16px 26px", borderTop: "1px solid var(--line)", background: "var(--paper)" }}>
            <div>
              <span style={{ fontSize: 12.5, color: "var(--ink-soft)" }}>Estimated total</span>
              <span style={{ display: "block", fontFamily: "var(--font-display)", fontSize: 24, fontWeight: 600 }}>${total}<span style={{ fontSize: 13, fontFamily: "var(--font-body)", color: "var(--ink-soft)", fontWeight: 500 }}> · pay after</span></span>
            </div>
            <div style={{ display: "flex", gap: 10 }}>
              {step > 0 && <button className="btn btn-ghost" onClick={back}>← Back</button>}
              <button className="btn btn-primary" onClick={next}>{step === 3 ? "Confirm booking" : "Continue →"}</button>
            </div>
          </div>
        )}
      </div>
      <style>{`
        @keyframes ovIn{from{opacity:0}to{opacity:1}}
        @keyframes modalIn{from{opacity:0;transform:translateY(16px) scale(.98)}to{opacity:1;transform:none}}
        @media(max-width:560px){.bk-svc,.bk-two{grid-template-columns:1fr !important;} .bk-size{grid-template-columns:1fr 1fr !important;} .bk-days{grid-template-columns:repeat(4,1fr) !important;}}
      `}</style>
    </div>
  );
}

function SummaryRow({ svc, size, form, days, total, pickupFee }) {
  const day = days.find(d => d.key === form.date);
  const rows = [
    [svc.name, `$${svc.price}`],
    [`${size.label} dog`, size.mult ? `+$${size.mult}` : "—"],
    ...(pickupFee ? [["Pick-up & drop-off", `+$${pickupFee}`]] : []),
  ];
  return (
    <div style={{ background: "var(--card)", borderRadius: 14, padding: "16px 18px" }}>
      <div style={{ fontSize: 12.5, fontWeight: 700, letterSpacing: "0.05em", textTransform: "uppercase", color: "var(--ink-soft)", marginBottom: 10 }}>Your booking</div>
      {form.dogName && <div style={{ fontSize: 14.5, marginBottom: 10 }}><strong>{form.dogName}</strong>{form.coat ? ` · ${form.coat}` : ""}{day ? ` · ${day.dow} ${day.mon} ${day.day} at ${form.time}` : ""}</div>}
      {rows.map(([l, v], i) => (
        <div key={i} style={{ display: "flex", justifyContent: "space-between", fontSize: 14, padding: "4px 0", color: "var(--ink-soft)" }}><span>{l}</span><span style={{ color: "var(--ink)", fontWeight: 600 }}>{v}</span></div>
      ))}
      <div style={{ display: "flex", justifyContent: "space-between", marginTop: 8, paddingTop: 10, borderTop: "1px solid var(--line)", fontWeight: 700 }}><span>Estimated total</span><span>${total}</span></div>
    </div>
  );
}

function Confirmation({ form, svc, size, total, days }) {
  const day = days.find(d => d.key === form.date);
  return (
    <div style={{ textAlign: "center", padding: "12px 0 8px" }}>
      <div style={{ width: 74, height: 74, borderRadius: 999, background: "var(--accent-2)", color: "#fff", display: "grid", placeItems: "center", margin: "0 auto 20px", animation: "pop .4s cubic-bezier(.2,1.4,.4,1)" }}>
        <svg viewBox="0 0 24 24" width="38" height="38" fill="none" stroke="#fff" strokeWidth="2.4" strokeLinecap="round" strokeLinejoin="round"><path d="m5 12.5 4.5 4.5L19 7"/></svg>
      </div>
      <h3 style={{ fontSize: 28 }}>See you soon, {form.ownerName.split(" ")[0] || "friend"}!</h3>
      <p style={{ fontSize: 15.5, color: "var(--ink-soft)", lineHeight: 1.55, marginTop: 12, maxWidth: 440, marginLeft: "auto", marginRight: "auto" }}>
        We've penciled in <strong style={{ color: "var(--ink)" }}>{form.dogName || "your pup"}</strong> for a <strong style={{ color: "var(--ink)" }}>{svc.name}</strong>
        {day ? <> on <strong style={{ color: "var(--ink)" }}>{day.dow}, {day.mon} {day.day}</strong> at <strong style={{ color: "var(--ink)" }}>{form.time}</strong></> : ""}. A confirmation text is on its way to {form.phone || "your phone"}.
      </p>
      <div style={{ background: "var(--card)", borderRadius: 14, padding: "16px 20px", margin: "24px auto 0", maxWidth: 360, textAlign: "left" }}>
        <div style={{ display: "flex", justifyContent: "space-between", fontSize: 14.5, padding: "4px 0" }}><span style={{ color: "var(--ink-soft)" }}>Service</span><span style={{ fontWeight: 600 }}>{svc.name}</span></div>
        <div style={{ display: "flex", justifyContent: "space-between", fontSize: 14.5, padding: "4px 0" }}><span style={{ color: "var(--ink-soft)" }}>Size</span><span style={{ fontWeight: 600 }}>{size.label}</span></div>
        <div style={{ display: "flex", justifyContent: "space-between", fontSize: 14.5, padding: "4px 0" }}><span style={{ color: "var(--ink-soft)" }}>Estimated total</span><span style={{ fontWeight: 700 }}>${total}</span></div>
      </div>
      <p style={{ fontSize: 13, color: "var(--ink-soft)", marginTop: 18 }}>No payment today — you'll settle up after the groom.</p>
      <style>{`@keyframes pop{from{transform:scale(0);opacity:0}to{transform:scale(1);opacity:1}}`}</style>
    </div>
  );
}

Object.assign(window, { BookingModal });
