// ============ Booking Modal — multi-step consultation flow ============

function BookingModal({ open, onClose }) {
  const [step, setStep] = React.useState(0);
  const [data, setData] = React.useState({
    specialty: null,
    doctor: null,
    date: null,
    slot: null,
    name: "",
    phone: "",
    email: "",
    contactPref: "whatsapp",
    notes: "",
  });

  React.useEffect(() => {
    if (!open) { setStep(0); }
  }, [open]);

  if (!open) return null;

  const D = window.EUROMED_DATA;
  const set = (k, v) => setData((x) => ({ ...x, [k]: v }));

  // Calendar — next 14 days, weekends "limited" (clinic note)
  const today = new Date(2026, 4, 25); // demo fixed: 25 May 2026 Mon
  const days = Array.from({ length: 14 }, (_, i) => {
    const d = new Date(today);
    d.setDate(d.getDate() + i);
    return d;
  });
  const SLOTS = ["10:00", "10:30", "11:00", "11:30", "14:00", "14:30", "15:30", "16:00", "16:30", "17:00", "17:30", "18:00"];
  const dayLabel = (d) => d.toLocaleDateString("en", { weekday: "short" });
  const dayNum = (d) => d.getDate();
  const isFri = (d) => d.getDay() === 5;

  const stepNames = ["Specialty", "Doctor", "Date & time", "Your details", "Confirm"];
  const canNext = [
    !!data.specialty,
    !!data.doctor,
    !!data.date && !!data.slot,
    data.name.trim().length > 1 && data.phone.trim().length > 5,
    true,
  ][step];

  const doctorsForSpec = data.specialty
    ? D.DOCTORS.filter((d) => {
        const s = data.specialty;
        if (s.id === "dental") return d.specialty === "Dental";
        if (s.id === "hair-transplant" || s.id === "plastic-surgery") return d.specialty === "Plastic Surgery";
        if (s.id === "cosmetic-aesthetic") return d.specialty === "Dermatology & Skin" || d.specialty === "Plastic Surgery";
        if (s.id === "family-medicine") return d.specialty === "Family Medicine";
        if (s.id === "wellness") return d.specialty === "Wellness";
        return true;
      })
    : [];

  return (
    <div className="modal-backdrop" onClick={onClose}>
      <div className="modal" onClick={(e) => e.stopPropagation()}>
        <div className="modal-head">
          <div>
            <span className="eyebrow no-rule" style={{ color: "var(--ink-3)" }}>
              {step < 4 ? `Step ${step + 1} / 5 · ${stepNames[step]}` : "All set"}
            </span>
            <h3 style={{ fontFamily: "var(--serif)", fontSize: 28, margin: "10px 0 0", lineHeight: 1.1, letterSpacing: "-0.01em" }}>
              {step === 0 && "Book a free consultation"}
              {step === 1 && "Choose a doctor"}
              {step === 2 && "Pick a date & time"}
              {step === 3 && "Your contact details"}
              {step === 4 && "Consultation requested"}
            </h3>
            <div className="modal-progress">
              {[0, 1, 2, 3, 4].map((i) => <div key={i} className={i <= step ? "done" : ""}></div>)}
            </div>
          </div>
          <button className="modal-close" onClick={onClose} aria-label="Close"><Icon.Close size={14} /></button>
        </div>

        <div className="modal-body">
          {/* Step 0 — Specialty */}
          {step === 0 && (
            <>
              <p style={{ color: "var(--ink-2)", fontSize: 14, marginTop: 0 }}>
                Which area is your visit about? Your initial consultation is free — typically 30 minutes with a doctor.
              </p>
              <div className="chip-grid">
                {D.SPECIALTIES.map((s) => (
                  <button key={s.id} className={"chip " + (data.specialty?.id === s.id ? "on" : "")} onClick={() => set("specialty", s)}>
                    <b>{s.name}</b>
                    <span>{s.intro}</span>
                  </button>
                ))}
              </div>
            </>
          )}

          {/* Step 1 — Doctor */}
          {step === 1 && (
            <>
              <p style={{ color: "var(--ink-2)", fontSize: 14, marginTop: 0 }}>
                Pick a consultant, or choose "any available" and we'll match you.
              </p>
              <div className="chip-grid">
                <button className={"chip " + (data.doctor === "any" ? "on" : "")} onClick={() => set("doctor", "any")}>
                  <b>Any available consultant</b>
                  <span>We'll match you — fastest path to an appointment.</span>
                </button>
                {doctorsForSpec.map((d) => (
                  <button key={d.id} className={"chip " + (data.doctor?.id === d.id ? "on" : "")} onClick={() => set("doctor", d)}>
                    <b>{d.name} {d.visiting && <span style={{ fontWeight: 400, color: "var(--ink-3)" }}>· visiting</span>}</b>
                    <span>{d.credentials} · {d.experience}</span>
                  </button>
                ))}
                {doctorsForSpec.length === 0 && (
                  <div style={{ gridColumn: "1 / -1", padding: 14, color: "var(--ink-3)", fontSize: 13 }}>
                    No verified profiles yet for this specialty. Select "any available" — we'll call to confirm.
                  </div>
                )}
              </div>
            </>
          )}

          {/* Step 2 — Date & time */}
          {step === 2 && (
            <>
              <p style={{ color: "var(--ink-2)", fontSize: 14, marginTop: 0 }}>
                Next available slots in the coming two weeks:
              </p>
              <label style={{ fontSize: 12, letterSpacing: "0.04em", color: "var(--ink-2)", fontWeight: 500 }}>Date</label>
              <div className="cal-grid">
                {days.map((d, i) => (
                  <button
                    key={i}
                    className={"cal-day " + (data.date && data.date.getTime() === d.getTime() ? "on" : "")}
                    disabled={isFri(d)}
                    onClick={() => { set("date", d); set("slot", null); }}
                  >
                    <small>{dayLabel(d)}</small>
                    {dayNum(d)}
                  </button>
                ))}
              </div>
              {data.date && (
                <>
                  <label style={{ fontSize: 12, letterSpacing: "0.04em", color: "var(--ink-2)", fontWeight: 500 }}>Time slot</label>
                  <div className="slot-grid">
                    {SLOTS.map((s) => (
                      <button
                        key={s}
                        className={"slot " + (data.slot === s ? "on" : "")}
                        disabled={["11:30", "14:00", "17:00"].includes(s) && Math.random() < 0.5}
                        onClick={() => set("slot", s)}
                      >
                        {s}
                      </button>
                    ))}
                  </div>
                </>
              )}
            </>
          )}

          {/* Step 3 — Details */}
          {step === 3 && (
            <>
              <p style={{ color: "var(--ink-2)", fontSize: 14, marginTop: 0 }}>
                We only collect what's needed to confirm your appointment. No medical history fields at this stage.
              </p>
              <div className="field-row">
                <div className="field">
                  <label>Full name</label>
                  <input value={data.name} onChange={(e) => set("name", e.target.value)} placeholder="Your name" />
                </div>
                <div className="field">
                  <label>Phone / WhatsApp</label>
                  <input value={data.phone} onChange={(e) => set("phone", e.target.value)} placeholder="+971 …" />
                </div>
              </div>
              <div className="field">
                <label>Email (optional)</label>
                <input value={data.email} onChange={(e) => set("email", e.target.value)} placeholder="you@example.com" />
              </div>
              <div className="field">
                <label>Preferred contact method</label>
                <div style={{ display: "flex", gap: 8 }}>
                  {["whatsapp", "phone", "email"].map((m) => (
                    <button key={m} className="chip" style={{
                      padding: "10px 16px", borderRadius: 8, flex: 1,
                      borderColor: data.contactPref === m ? "var(--teal)" : "var(--line-strong)",
                      background: data.contactPref === m ? "var(--teal-soft)" : "var(--paper)",
                    }} onClick={() => set("contactPref", m)}>
                      <b style={{ textTransform: "capitalize" }}>{m}</b>
                    </button>
                  ))}
                </div>
              </div>
              <div className="field">
                <label>Anything else? (optional)</label>
                <textarea value={data.notes} onChange={(e) => set("notes", e.target.value)} rows="3" placeholder="e.g. preferred language, returning patient…" />
              </div>
              <div style={{ fontSize: 12, color: "var(--ink-3)", lineHeight: 1.55 }}>
                By submitting you agree to be contacted about your appointment. We store minimal personal information — see our patient privacy notice. <strong>No medical history fields collected at this stage.</strong>
              </div>
            </>
          )}

          {/* Step 4 — Confirmation */}
          {step === 4 && (
            <>
              <div className="confirm-icon">
                <svg width="28" height="28" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                  <polyline points="20 6 9 17 4 12"></polyline>
                </svg>
              </div>
              <p style={{ textAlign: "center", color: "var(--ink-2)", fontSize: 15, lineHeight: 1.6, maxWidth: "44ch", margin: "0 auto 28px" }}>
                Thanks, <strong>{data.name || "—"}</strong>. We've received your request. A coordinator will confirm by{" "}
                <strong>{data.contactPref === "whatsapp" ? "WhatsApp" : data.contactPref}</strong> within one working hour during clinic hours.
              </p>
              <div className="book-summary">
                <div className="book-summary-row"><label>Specialty</label><span>{data.specialty?.name || "—"}</span></div>
                <div className="book-summary-row"><label>Doctor</label><span>{data.doctor === "any" ? "Any available consultant" : (data.doctor?.name || "—")}</span></div>
                <div className="book-summary-row"><label>When</label><span>{data.date ? data.date.toLocaleDateString("en", { weekday: "long", month: "long", day: "numeric" }) : "—"} · {data.slot || "—"}</span></div>
                <div className="book-summary-row"><label>Contact</label><span>{data.phone || "—"} ({data.contactPref})</span></div>
              </div>
              <div style={{ display: "flex", gap: 10 }}>
                <button className="btn btn-primary" style={{ flex: 1, justifyContent: "center" }} onClick={onClose}>
                  Done
                </button>
                <a className="btn btn-ghost" style={{ flex: 1, justifyContent: "center" }} href="https://api.whatsapp.com/send?phone=97148945000" target="_blank" rel="noreferrer">
                  <Icon.WhatsApp size={14}/> Open WhatsApp
                </a>
              </div>
            </>
          )}

          {/* Footer nav */}
          {step < 4 && (
            <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginTop: 28, paddingTop: 22, borderTop: "1px solid var(--line)" }}>
              <button className="btn-link" disabled={step === 0} style={{ opacity: step === 0 ? 0.3 : 1 }} onClick={() => setStep(Math.max(0, step - 1))}>
                ← Back
              </button>
              <button className="btn btn-primary" disabled={!canNext} style={{ opacity: canNext ? 1 : 0.4 }} onClick={() => setStep(step + 1)}>
                {step === 3 ? "Submit request" : "Continue"} <Icon.Arrow size={14}/>
              </button>
            </div>
          )}
        </div>
      </div>
    </div>
  );
}

window.BookingModal = BookingModal;
