// THE MOST — booking modal flow (Fresha-style multi-step)
const { useState: useStateB, useEffect: useEffectB, useMemo: useMemoB, useRef: useRefB } = React;

function BookingModal({ open, onClose, initialService }) {
  const [step, setStep] = useStateB(0);
  const [service, setService] = useStateB(initialService || null);
  const [stylist, setStylist] = useStateB("any");
  const [date, setDate] = useStateB(null);
  const [time, setTime] = useStateB(null);
  const [client, setClient] = useStateB({ name: "", phone: "", email: "", notes: "" });
  const [confirmed, setConfirmed] = useStateB(false);

  useEffectB(() => {
    if (open) {
      if (initialService) {
        setService(initialService);
        setStep(1);
      } else {
        setStep(0);
      }
      setStylist("any");
      setDate(null);
      setTime(null);
      setConfirmed(false);
      document.body.style.overflow = "hidden";
    } else {
      document.body.style.overflow = "";
    }
    return () => { document.body.style.overflow = ""; };
  }, [open, initialService]);

  if (!open) return null;

  const steps = ["Service", "Stylist", "Date & time", "Your details", "Confirm"];

  const next = () => setStep((s) => Math.min(s + 1, steps.length - 1));
  const back = () => setStep((s) => Math.max(s - 1, 0));

  const canNext = () => {
    if (step === 0) return !!service;
    if (step === 1) return !!stylist;
    if (step === 2) return !!date && !!time;
    if (step === 3) return client.name.trim() && (client.phone.trim() || client.email.trim());
    return true;
  };

  const submit = () => {
    setConfirmed(true);
  };

  return (
    <div className="tm-modal-wrap" role="dialog" aria-modal="true">
      <div className="tm-modal-veil" onClick={onClose}/>
      <div className="tm-modal">
        <header className="tm-modal-head">
          <div className="tm-modal-brand">
            <Wordmark size={14} showTagline/>
          </div>
          <div className="tm-modal-progress">
            {steps.map((s, i) => (
              <div key={i} className={`tm-progress-step ${i === step ? "is-active" : ""} ${i < step ? "is-done" : ""}`}>
                <span className="tm-progress-num">{String(i + 1).padStart(2, "0")}</span>
                <span className="tm-progress-label">{s}</span>
              </div>
            ))}
          </div>
          <button className="tm-modal-close" onClick={onClose} aria-label="Close">×</button>
        </header>

        <div className="tm-modal-body">
          {confirmed ? (
            <BookingConfirmed service={service} stylist={stylist} date={date} time={time} client={client} onClose={onClose}/>
          ) : (
            <>
              {step === 0 && <StepService selected={service} onSelect={setService}/>}
              {step === 1 && <StepStylist service={service} stylist={stylist} onSelect={setStylist}/>}
              {step === 2 && <StepWhen date={date} time={time} onDate={setDate} onTime={setTime}/>}
              {step === 3 && <StepDetails value={client} onChange={setClient}/>}
              {step === 4 && <StepReview service={service} stylist={stylist} date={date} time={time} client={client}/>}
            </>
          )}
        </div>

        {!confirmed && (
          <footer className="tm-modal-foot">
            <button className="tm-btn tm-btn-ghost" onClick={step === 0 ? onClose : back}>
              {step === 0 ? "Cancel" : "← Back"}
            </button>
            <div className="tm-modal-foot-meta">
              {service && (
                <div className="tm-foot-summary">
                  <span className="tm-foot-svc">{service.name}</span>
                  {service.duration && <span className="tm-foot-dur">{service.duration}</span>}
                  {service.price && <span className="tm-foot-price">{service.price}</span>}
                </div>
              )}
            </div>
            {step === steps.length - 1 ? (
              <button className="tm-btn tm-btn-primary" onClick={submit}>Reserve appointment</button>
            ) : (
              <button className="tm-btn tm-btn-primary" disabled={!canNext()} onClick={next}>
                Continue →
              </button>
            )}
          </footer>
        )}
      </div>
    </div>
  );
}

// Step 0: choose service
function StepService({ selected, onSelect }) {
  const sig = window.SALON_DATA.signature;
  const menu = window.SALON_DATA.menu;
  const [cat, setCat] = useStateB("Signature");
  const cats = ["Signature", ...Object.keys(menu)];
  const items = cat === "Signature" ? sig.map((s) => ({
    id: s.id, name: s.name, duration: s.duration, price: s.price, category: s.category,
  })) : menu[cat].map(([n, d, p]) => ({
    id: `${cat}-${n}`, name: n, duration: d, price: `AED ${p}`, category: cat,
  }));

  return (
    <div className="tm-step tm-step-service">
      <h3 className="tm-step-title">Choose a service</h3>
      <p className="tm-step-sub">Single appointment, one service. Add more after the first is held.</p>
      <div className="tm-svc-cats">
        {cats.map((c) => (
          <button key={c} className={`tm-pill ${cat === c ? "is-active" : ""}`} onClick={() => setCat(c)}>{c}</button>
        ))}
      </div>
      <div className="tm-svc-list">
        {items.map((it) => (
          <button
            key={it.id}
            className={`tm-svc-row ${selected?.id === it.id ? "is-selected" : ""}`}
            onClick={() => onSelect(it)}
          >
            <div className="tm-svc-row-main">
              <div className="tm-svc-row-name">{it.name}</div>
              <div className="tm-svc-row-meta">
                <span>{it.category}</span>
                <span className="tm-svc-dot">·</span>
                <span>{it.duration}</span>
              </div>
            </div>
            <div className="tm-svc-row-price">{it.price}</div>
            <div className="tm-svc-row-mark">
              {selected?.id === it.id ? "✓" : "+"}
            </div>
          </button>
        ))}
      </div>
    </div>
  );
}

// Step 1: stylist
function StepStylist({ service, stylist, onSelect }) {
  const options = [
    { id: "any", name: "Any available stylist", note: "We'll match you to the next free chair.", flag: "Fastest" },
    { id: "alaa", name: "Alaa", note: "Named in five-star reviews.", flag: "Awaiting consent" },
    { id: "noor", name: "Noor", note: "Named in five-star reviews.", flag: "Awaiting consent" },
    { id: "senior", name: "Senior stylist (Colour)", note: "Specialist for balayage & complex colour.", flag: "On request" },
  ];
  return (
    <div className="tm-step">
      <h3 className="tm-step-title">Pick a stylist</h3>
      <p className="tm-step-sub">Final team names show once each stylist has approved their card. Until then, "any" is the safe pick.</p>
      <div className="tm-stylist-options">
        {options.map((o) => (
          <button
            key={o.id}
            className={`tm-stylist-opt ${stylist === o.id ? "is-selected" : ""}`}
            onClick={() => onSelect(o.id)}
          >
            <div className="tm-stylist-opt-avatar">
              {o.id === "any" ? (
                <span className="tm-stylist-opt-glyph">✻</span>
              ) : (
                <span className="tm-stylist-opt-init">{o.name[0]}</span>
              )}
            </div>
            <div className="tm-stylist-opt-body">
              <div className="tm-stylist-opt-name">{o.name}</div>
              <div className="tm-stylist-opt-note">{o.note}</div>
            </div>
            <div className="tm-stylist-opt-flag">{o.flag}</div>
            <div className="tm-stylist-opt-mark">{stylist === o.id ? "✓" : ""}</div>
          </button>
        ))}
      </div>
    </div>
  );
}

// Step 2: date & time
function StepWhen({ date, time, onDate, onTime }) {
  const today = new Date(2026, 4, 25); // May 25 2026 (anchored)
  const [monthOffset, setMonthOffset] = useStateB(0);
  const monthStart = new Date(today.getFullYear(), today.getMonth() + monthOffset, 1);
  const monthLabel = monthStart.toLocaleDateString("en-GB", { month: "long", year: "numeric" });
  const daysInMonth = new Date(monthStart.getFullYear(), monthStart.getMonth() + 1, 0).getDate();
  const firstDow = (monthStart.getDay() + 6) % 7; // Mon=0

  const dates = [];
  for (let i = 0; i < firstDow; i++) dates.push(null);
  for (let d = 1; d <= daysInMonth; d++) {
    dates.push(new Date(monthStart.getFullYear(), monthStart.getMonth(), d));
  }

  const isPast = (d) => d && d < new Date(today.getFullYear(), today.getMonth(), today.getDate());
  const isSunday = (d) => d && d.getDay() === 0;
  const dateKey = (d) => d ? `${d.getFullYear()}-${d.getMonth()}-${d.getDate()}` : null;

  // Pseudo-deterministic time slots
  const slots = useMemoB(() => {
    if (!date) return [];
    const all = [];
    for (let h = 10; h < 21; h++) {
      for (const m of [0, 30]) {
        const taken = ((date.getDate() * 13 + h * 7 + m) % 11) < 4; // ~36% taken
        all.push({ label: `${String(h).padStart(2, "0")}:${String(m).padStart(2, "0")}`, taken });
      }
    }
    return all;
  }, [date]);

  return (
    <div className="tm-step tm-step-when">
      <h3 className="tm-step-title">Choose a date and time</h3>
      <p className="tm-step-sub">Live availability syncs with Fresha at confirmation. Sundays are marked as <em>confirming</em> until the salon resolves listed hours.</p>
      <div className="tm-when-grid">
        <div className="tm-cal">
          <div className="tm-cal-head">
            <button className="tm-cal-nav" onClick={() => setMonthOffset(monthOffset - 1)} disabled={monthOffset === 0}>‹</button>
            <div className="tm-cal-month">{monthLabel}</div>
            <button className="tm-cal-nav" onClick={() => setMonthOffset(monthOffset + 1)}>›</button>
          </div>
          <div className="tm-cal-dow">
            {["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"].map((d) => (
              <span key={d}>{d}</span>
            ))}
          </div>
          <div className="tm-cal-grid">
            {dates.map((d, i) => {
              if (!d) return <span key={i} className="tm-cal-cell tm-cal-empty"/>;
              const past = isPast(d);
              const sunday = isSunday(d);
              const selected = dateKey(d) === dateKey(date);
              return (
                <button
                  key={i}
                  disabled={past}
                  className={`tm-cal-cell ${past ? "is-past" : ""} ${sunday ? "is-sunday" : ""} ${selected ? "is-selected" : ""}`}
                  onClick={() => { onDate(d); onTime(null); }}
                >
                  <span className="tm-cal-num">{d.getDate()}</span>
                  {sunday && <span className="tm-cal-flag">?</span>}
                </button>
              );
            })}
          </div>
          <div className="tm-cal-legend">
            <span><span className="tm-dot tm-dot-sel"/> Selected</span>
            <span><span className="tm-dot tm-dot-sun"/> Sunday — confirming</span>
            <span><span className="tm-dot tm-dot-past"/> Past</span>
          </div>
        </div>

        <div className="tm-slots">
          <div className="tm-slots-head">
            <div>{date ? date.toLocaleDateString("en-GB", { weekday: "long", day: "numeric", month: "long" }) : "Pick a date first"}</div>
            {date && <div className="tm-muted">{slots.filter((s) => !s.taken).length} slots open</div>}
          </div>
          {date ? (
            <div className="tm-slots-grid">
              {slots.map((s, i) => (
                <button
                  key={i}
                  disabled={s.taken}
                  className={`tm-slot ${s.taken ? "is-taken" : ""} ${time === s.label ? "is-selected" : ""}`}
                  onClick={() => onTime(s.label)}
                >
                  {s.label}
                </button>
              ))}
            </div>
          ) : (
            <div className="tm-slots-empty">Choose a date on the left to see open slots.</div>
          )}
        </div>
      </div>
    </div>
  );
}

// Step 3: client details
function StepDetails({ value, onChange }) {
  const set = (k, v) => onChange({ ...value, [k]: v });
  return (
    <div className="tm-step tm-step-details">
      <h3 className="tm-step-title">Your details</h3>
      <p className="tm-step-sub">A first name is enough; we&rsquo;ll only call if a stylist needs to confirm a colour consultation.</p>
      <div className="tm-form">
        <label className="tm-field">
          <span className="tm-field-label">Name</span>
          <input className="tm-input" value={value.name} onChange={(e) => set("name", e.target.value)} placeholder="As you'd like to be greeted"/>
        </label>
        <label className="tm-field">
          <span className="tm-field-label">Mobile <span className="tm-muted">or email</span></span>
          <input className="tm-input" value={value.phone} onChange={(e) => set("phone", e.target.value)} placeholder="+971 5x xxx xxxx"/>
        </label>
        <label className="tm-field">
          <span className="tm-field-label">Email</span>
          <input className="tm-input" type="email" value={value.email} onChange={(e) => set("email", e.target.value)} placeholder="optional"/>
        </label>
        <label className="tm-field tm-field-wide">
          <span className="tm-field-label">Notes for your stylist <span className="tm-muted">optional</span></span>
          <textarea className="tm-input" rows="3" value={value.notes} onChange={(e) => set("notes", e.target.value)} placeholder="Tone direction, hair length, occasion…"/>
        </label>
      </div>
      <div className="tm-form-foot">
        <label className="tm-check">
          <input type="checkbox" defaultChecked/>
          <span>Send me a 24-hour reminder by SMS.</span>
        </label>
        <div className="tm-muted tm-form-priv">
          Your details are held only for this booking. Women-only sanctuary — no third-party marketing.
        </div>
      </div>
    </div>
  );
}

// Step 4: review
function StepReview({ service, stylist, date, time, client }) {
  const stylistLabel = {
    any: "Any available stylist",
    alaa: "Alaa",
    noor: "Noor",
    senior: "Senior stylist (Colour)",
  }[stylist];
  return (
    <div className="tm-step tm-step-review">
      <h3 className="tm-step-title">Looks right?</h3>
      <p className="tm-step-sub">No card needed yet — Fresha will request payment details only at the chair, or for colour deposits if applicable.</p>
      <div className="tm-review-card">
        <div className="tm-review-card-head">
          <div className="tm-review-card-title">{service?.name}</div>
          <div className="tm-review-card-price">{service?.price}</div>
        </div>
        <ul className="tm-review-lines">
          <li><span>Stylist</span><span>{stylistLabel}</span></li>
          <li><span>Date</span><span>{date?.toLocaleDateString("en-GB", { weekday: "long", day: "numeric", month: "long" })}</span></li>
          <li><span>Time</span><span>{time}</span></li>
          <li><span>Duration</span><span>{service?.duration}</span></li>
          <li><span>For</span><span>{client.name || "—"}</span></li>
          <li><span>Contact</span><span>{client.phone || client.email || "—"}</span></li>
        </ul>
        {client.notes && (
          <div className="tm-review-notes">
            <div className="tm-eyebrow">Notes</div>
            <p>{client.notes}</p>
          </div>
        )}
      </div>
      <div className="tm-review-policy">
        <p>By reserving you agree to the salon&rsquo;s 4-hour cancellation window. We&rsquo;ll text you a reminder the day before.</p>
      </div>
    </div>
  );
}

// Confirmed screen
function BookingConfirmed({ service, stylist, date, time, client, onClose }) {
  const ref = useMemoB(() => "TMD-" + String(Math.floor(Math.random() * 90000) + 10000), []);
  return (
    <div className="tm-confirmed">
      <div className="tm-confirmed-art">
        <div className="tm-confirmed-glyph">
          <svg width="48" height="48" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.2">
            <path d="M4 12.5l5 5L20 6.5"/>
          </svg>
        </div>
        <div className="tm-confirmed-eye">Reservation held</div>
      </div>
      <h3 className="tm-confirmed-title"><em>Meet yourself</em> on {date?.toLocaleDateString("en-GB", { day: "numeric", month: "long" })} at {time}.</h3>
      <p className="tm-confirmed-sub">
        Your chair is on hold for fifteen minutes while Fresha confirms. A reminder will reach
        you the day before — and the kettle will already be on.
      </p>
      <div className="tm-confirmed-card">
        <div className="tm-confirmed-row"><span>Reference</span><span className="tm-mono">{ref}</span></div>
        <div className="tm-confirmed-row"><span>Service</span><span>{service?.name}</span></div>
        <div className="tm-confirmed-row"><span>For</span><span>{client.name}</span></div>
        <div className="tm-confirmed-row"><span>Where</span><span>Bldg 6 · d3 · Dubai</span></div>
      </div>
      <div className="tm-confirmed-ctas">
        <a className="tm-btn tm-btn-primary" href={window.SALON_DATA.contact.fresha} target="_blank" rel="noreferrer">
          Open on Fresha to finalise
        </a>
        <button className="tm-btn tm-btn-ghost" onClick={onClose}>Close</button>
      </div>
      <div className="tm-confirmed-foot tm-muted">
        Need to change? Call {window.SALON_DATA.contact.landline} — we answer Mon–Sat.
      </div>
    </div>
  );
}

Object.assign(window, { BookingModal });
