/* Hortman Clinics — modal flows */
const { useState: useS, useEffect: useE } = React;
const HCIcon = window.HC.Icon;

/* ---------- shared modal wrapper ---------- */
const ModalShell = ({ onClose, children, small, className = "" }) => {
  useE(() => {
    const k = (e) => e.key === "Escape" && onClose();
    document.addEventListener("keydown", k);
    document.body.style.overflow = "hidden";
    return () => {
      document.removeEventListener("keydown", k);
      document.body.style.overflow = "";
    };
  }, [onClose]);
  return (
    <div className="modal-back" onClick={onClose}>
      <div className={"modal " + (small ? "small " : "") + className} onClick={(e) => e.stopPropagation()}>
        <button className="modal-close" onClick={onClose} aria-label="Close">
          <HCIcon name="close" size={16} />
        </button>
        {children}
      </div>
    </div>
  );
};

/* ---------- Doctor profile modal ---------- */
const DoctorModal = ({ doctor, onClose, onBook }) => {
  if (!doctor) return null;
  return (
    <ModalShell onClose={onClose}>
      <div className="doctor-modal">
        <div className="doctor-modal-photo">
          <img src={doctor.img} alt={doctor.name} />
        </div>
        <div className="doctor-modal-body">
          <div className="role">{doctor.specialty}</div>
          <h3>{doctor.name}</h3>
          <div style={{ display: "flex", gap: 12, marginTop: 12 }}>
            <span className={"verified-pill " + (doctor.verified ? "" : "pending-pill")}>
              {doctor.verified ? "Credentials verified" : "Pending verification"}
            </span>
          </div>
          <p style={{ marginTop: 18, color: "var(--ink-2)", fontSize: 14, lineHeight: 1.6 }}>
            {doctor.bio}
          </p>

          <ul className="cred-list">
            {doctor.credentials.map(([k, v], i) => (
              <li key={i}>
                <span className="k">{k}</span>
                <span>{v}</span>
              </li>
            ))}
            <li>
              <span className="k">Location</span>
              <span>{doctor.location}</span>
            </li>
            <li>
              <span className="k">Languages</span>
              <span>{doctor.languages}</span>
            </li>
          </ul>

          <div className="label-mono" style={{ marginTop: 18 }}>Common consultations</div>
          <div style={{ display: "flex", flexWrap: "wrap", gap: 8, marginTop: 10 }}>
            {doctor.treatments.map((t) => (
              <span key={t} style={{
                padding: "6px 12px",
                background: "var(--paper-2)",
                fontSize: 12,
                color: "var(--ink-2)"
              }}>{t}</span>
            ))}
          </div>

          <div style={{ display: "flex", gap: 12, marginTop: 28, flexWrap: "wrap" }}>
            <button className="btn btn-primary" onClick={() => { onClose(); onBook(doctor); }}>
              Book with {doctor.name.split(" ")[1]} <HCIcon name="arrow" />
            </button>
            <a className="btn btn-ghost" href={window.HC_DATA.contact.whatsappHref} target="_blank" rel="noopener">
              Ask a question
            </a>
          </div>
        </div>
      </div>
    </ModalShell>
  );
};

/* ---------- Consent (Before/After) request modal ---------- */
const ConsentModal = ({ onClose }) => {
  const [sent, setSent] = useS(false);
  const [area, setArea] = useS("");

  if (sent) {
    return (
      <ModalShell onClose={onClose} small>
        <div className="consent-modal">
          <div className="booking-success" style={{ padding: 12 }}>
            <div className="check"><HCIcon name="check" size={28} /></div>
            <h3 className="display">Request received</h3>
            <p className="lead" style={{ fontSize: 14 }}>
              A patient coordinator will reach out within one working
              day with consented case examples — only for cases that
              match your concern, and only with explicit patient consent
              on file.
            </p>
          </div>
        </div>
      </ModalShell>
    );
  }

  return (
    <ModalShell onClose={onClose} small>
      <div className="consent-modal">
        <div className="eyebrow">Consent-gated request</div>
        <h3 style={{ marginTop: 8 }}>Request consented case examples</h3>
        <p className="lead">
          Tell us which treatment area you are considering. We will share
          relevant before-and-after imagery only where the specific patient
          has given written consent and the imagery passes our DHA review.
        </p>

        <div className="compliance-note">
          <strong style={{ color: "var(--ink)" }}>Compliance:</strong> In
          line with UAE DHA advertising rules, we do not display patient
          imagery without explicit patient consent. Shared examples remain
          confidential and are returned at the end of your enquiry.
        </div>

        <form onSubmit={(e) => { e.preventDefault(); setSent(true); }}>
          <div className="field-grid">
            <div className="field">
              <label>Full name</label>
              <input type="text" required placeholder="Your name" />
            </div>
            <div className="field">
              <label>Email</label>
              <input type="email" required placeholder="you@example.com" />
            </div>
            <div className="field">
              <label>Mobile (WhatsApp preferred)</label>
              <input type="tel" required placeholder="+971 …" />
            </div>
            <div className="field">
              <label>Treatment area</label>
              <select value={area} onChange={(e) => setArea(e.target.value)} required>
                <option value="" disabled>Select a specialty</option>
                {window.HC_DATA.specialties.map((s) => (
                  <option key={s.id} value={s.id}>{s.name.replace(/\u00a0/g, " ")}</option>
                ))}
              </select>
            </div>
          </div>
          <div className="field" style={{ marginTop: 14 }}>
            <label>What concern would you like examples for?</label>
            <textarea placeholder="Briefly describe your concern (e.g. melasma on cheeks, nasal-tip refinement, beard density)…" />
          </div>
          <label className="field-checkbox">
            <input type="checkbox" required />
            <span>I understand examples are shared confidentially and only where the specific patient has provided written consent.</span>
          </label>
          <button className="btn btn-primary" type="submit" style={{ marginTop: 22 }}>
            Submit request <HCIcon name="arrow" />
          </button>
        </form>
      </div>
    </ModalShell>
  );
};

/* ---------- Booking flow ---------- */
const stepDefs = [
  { id: "specialty", title: "Specialty" },
  { id: "location",  title: "Location"  },
  { id: "time",      title: "Time"      },
  { id: "details",   title: "Your details" }
];

const BookingModal = ({ onClose, prefill }) => {
  const [step, setStep] = useS(0);
  const [data, setData] = useS({
    specialty: prefill?.specialty || "",
    doctorId:  prefill?.doctorId  || "",
    location:  prefill?.location  || "",
    day:       "",
    time:      "",
    name: "", email: "", phone: "",
    notes: prefill?.notes || "",
    consent: false
  });
  const [submitted, setSubmitted] = useS(false);

  const update = (k, v) => setData((d) => ({ ...d, [k]: v }));

  const canNext = () => {
    if (step === 0) return !!data.specialty;
    if (step === 1) return !!data.location;
    if (step === 2) return !!data.day && !!data.time;
    if (step === 3) return data.name && data.email && data.phone && data.consent;
    return false;
  };

  const next = () => {
    if (step === 3) setSubmitted(true);
    else setStep((s) => s + 1);
  };

  const days = (() => {
    const out = [];
    const today = new Date();
    let added = 0;
    for (let i = 1; added < 7; i++) {
      const d = new Date(today);
      d.setDate(d.getDate() + i);
      if (d.getDay() === 0) continue; // skip Sunday — clinic closed
      out.push(d);
      added++;
    }
    return out;
  })();

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

  const specialtyName = (id) => window.HC_DATA.specialties.find((s) => s.id === id)?.name.replace(/\u00a0/g, " ") || "—";
  const locationName  = (id) => window.HC_DATA.locations.find((l) => l.id === id)?.name || "—";
  const fmtDay = (d) => d ? new Date(d).toLocaleDateString("en-GB", { weekday: "short", day: "numeric", month: "short" }) : "—";

  return (
    <ModalShell onClose={onClose}>
      <div className="booking">
        <aside className="booking-aside">
          <div className="wordmark">HORTMAN</div>
          <div className="label-mono" style={{ color: "rgba(246,241,232,0.5)", marginBottom: 12 }}>Consultation booking</div>
          <div className="booking-steps">
            {stepDefs.map((s, i) => (
              <div
                key={s.id}
                className={"booking-step-item " + (i === step ? "active" : i < step ? "done" : "")}
              >
                <div className="pill">
                  {i < step ? <HCIcon name="check" size={14} /> : (i + 1).toString().padStart(2, "0")}
                </div>
                <div>
                  <div style={{ fontSize: 12, letterSpacing: "0.08em", textTransform: "uppercase", opacity: 0.6 }}>
                    Step {i + 1}
                  </div>
                  <div style={{ fontSize: 14 }}>{s.title}</div>
                </div>
              </div>
            ))}
          </div>
          <div className="booking-foot">
            Need help?<br/>
            <a href={window.HC_DATA.contact.whatsappHref} target="_blank" rel="noopener"
               style={{ color: "var(--bronze-2)" }}>WhatsApp the team →</a>
          </div>
        </aside>

        <div className="booking-main">
          {submitted ? (
            <div className="booking-success">
              <div className="check"><HCIcon name="check" size={28} /></div>
              <div className="eyebrow">Request received</div>
              <h3 className="display">Thank you, {data.name.split(" ")[0]}.</h3>
              <p className="lead" style={{ maxWidth: 460, fontSize: 14 }}>
                A patient coordinator will confirm your consultation
                within two hours during clinic hours. We'll send
                a WhatsApp confirmation to <strong>{data.phone}</strong>.
              </p>
              <div className="summary-card">
                <div className="k">Specialty</div>      <div>{specialtyName(data.specialty)}</div>
                <div className="k">Location</div>       <div>{locationName(data.location)}</div>
                <div className="k">Requested time</div> <div>{fmtDay(data.day)} · {data.time}</div>
                <div className="k">Email</div>          <div>{data.email}</div>
              </div>
              <div style={{ display: "flex", gap: 12, marginTop: 22 }}>
                <button className="btn btn-primary" onClick={onClose}>Close</button>
                <a className="btn btn-ghost" href={window.HC_DATA.contact.whatsappHref} target="_blank" rel="noopener">
                  Continue on WhatsApp
                </a>
              </div>
              <p style={{ fontSize: 11, color: "var(--muted)", marginTop: 24, letterSpacing: "0.04em" }}>
                {window.HC_DATA.contact.licence}
              </p>
            </div>
          ) : (
            <>
              {step === 0 && (
                <>
                  <div className="eyebrow">Step 01 of 04</div>
                  <h3>Which area shall we consult on?</h3>
                  <p className="lead">All consultations begin with a face-to-face conversation with a specialist — no treatment is booked at this stage.</p>
                  <div className="booking-grid">
                    {window.HC_DATA.specialties.map((s) => (
                      <button
                        key={s.id}
                        className={"book-option" + (data.specialty === s.id ? " selected" : "")}
                        onClick={() => update("specialty", s.id)}
                        type="button"
                      >
                        <div className="icon-wrap" style={{ color: data.specialty === s.id ? "var(--jade)" : "var(--ink-2)" }}>
                          <HCIcon name={window.HC.specialtyIcon(s.id)} size={26} />
                        </div>
                        <div className="title">{s.name.replace(/\u00a0/g, " ")}</div>
                        <div className="sub">{s.count}</div>
                      </button>
                    ))}
                    <button
                      className={"book-option" + (data.specialty === "unsure" ? " selected" : "")}
                      onClick={() => update("specialty", "unsure")}
                      type="button"
                    >
                      <div className="icon-wrap"><HCIcon name="info" size={26} /></div>
                      <div className="title">Not sure yet</div>
                      <div className="sub">Help me find the right specialist</div>
                    </button>
                  </div>
                </>
              )}

              {step === 1 && (
                <>
                  <div className="eyebrow">Step 02 of 04</div>
                  <h3>Which clinic suits you?</h3>
                  <p className="lead">Sheikh Zayed Road carries the full offer including surgical suites; Jumeirah focuses on aesthetics, dermatology and wellness.</p>
                  <div className="booking-grid">
                    {window.HC_DATA.locations.map((l) => (
                      <button
                        key={l.id}
                        className={"book-option" + (data.location === l.id ? " selected" : "")}
                        onClick={() => update("location", l.id)}
                        type="button"
                      >
                        <div className="icon-wrap"><HCIcon name="pin" size={22} /></div>
                        <div className="title">{l.name}</div>
                        <div className="sub">{l.sub}</div>
                        <div className="sub" style={{ marginTop: 6, color: "var(--jade)" }}>{l.services}</div>
                      </button>
                    ))}
                  </div>
                </>
              )}

              {step === 2 && (
                <>
                  <div className="eyebrow">Step 03 of 04</div>
                  <h3>Pick a day &amp; time</h3>
                  <p className="lead">Tentative — your coordinator confirms with the specialist's diary. Clinic hours Mon–Sat, 10:00–20:00.</p>

                  <div className="label-mono" style={{ marginBottom: 8 }}>Day</div>
                  <div style={{ display: "grid", gridTemplateColumns: "repeat(7, 1fr)", gap: 6 }}>
                    {days.map((d) => {
                      const k = d.toISOString().slice(0, 10);
                      return (
                        <button
                          key={k}
                          onClick={() => update("day", k)}
                          type="button"
                          className={"book-option"}
                          style={{
                            padding: "12px 6px",
                            textAlign: "center",
                            borderColor: data.day === k ? "var(--jade)" : "var(--line)",
                            background: data.day === k ? "var(--jade-soft)" : "transparent"
                          }}
                        >
                          <div className="sub" style={{ fontSize: 10 }}>
                            {d.toLocaleDateString("en-GB", { weekday: "short" }).toUpperCase()}
                          </div>
                          <div className="title" style={{ fontSize: 18 }}>
                            {d.getDate()}
                          </div>
                          <div className="sub" style={{ fontSize: 10 }}>
                            {d.toLocaleDateString("en-GB", { month: "short" }).toUpperCase()}
                          </div>
                        </button>
                      );
                    })}
                  </div>

                  <div className="label-mono" style={{ marginTop: 22, marginBottom: 8 }}>Time</div>
                  <div style={{ display: "grid", gridTemplateColumns: "repeat(7, 1fr)", gap: 6 }}>
                    {slots.map((s) => (
                      <button
                        key={s}
                        onClick={() => update("time", s)}
                        type="button"
                        className="book-option"
                        style={{
                          padding: "10px 6px",
                          textAlign: "center",
                          borderColor: data.time === s ? "var(--jade)" : "var(--line)",
                          background: data.time === s ? "var(--jade-soft)" : "transparent"
                        }}
                      >
                        <div className="title" style={{ fontSize: 14 }}>{s}</div>
                      </button>
                    ))}
                  </div>
                </>
              )}

              {step === 3 && (
                <>
                  <div className="eyebrow">Step 04 of 04</div>
                  <h3>Your details</h3>
                  <p className="lead">We only ask for what's needed to confirm your consultation. No medical history at this stage — that's discussed in person.</p>
                  <div className="field-grid">
                    <div className="field">
                      <label>Full name</label>
                      <input type="text" required value={data.name} onChange={(e) => update("name", e.target.value)} placeholder="As on your ID" />
                    </div>
                    <div className="field">
                      <label>Mobile (WhatsApp)</label>
                      <input type="tel" required value={data.phone} onChange={(e) => update("phone", e.target.value)} placeholder="+971 …" />
                    </div>
                    <div className="field" style={{ gridColumn: "1 / -1" }}>
                      <label>Email</label>
                      <input type="email" required value={data.email} onChange={(e) => update("email", e.target.value)} placeholder="you@example.com" />
                    </div>
                    <div className="field" style={{ gridColumn: "1 / -1" }}>
                      <label>Anything we should know? (optional)</label>
                      <textarea value={data.notes} onChange={(e) => update("notes", e.target.value)}
                                placeholder="Brief note for your coordinator (no medical details required)" />
                    </div>
                  </div>
                  <label className="field-checkbox">
                    <input type="checkbox" checked={data.consent}
                           onChange={(e) => update("consent", e.target.checked)} required />
                    <span>I consent to Hortman Clinics contacting me about this request. No medical details are required on this form; my history will be discussed at the in-person consultation.</span>
                  </label>

                  <div className="summary-card" style={{ marginTop: 18 }}>
                    <div className="k">Specialty</div>      <div>{specialtyName(data.specialty)}</div>
                    <div className="k">Location</div>       <div>{locationName(data.location)}</div>
                    <div className="k">Requested time</div> <div>{fmtDay(data.day)} · {data.time || "—"}</div>
                  </div>
                </>
              )}

              <div className="booking-actions">
                {step > 0 ? (
                  <button className="btn btn-ghost" onClick={() => setStep((s) => s - 1)}>
                    ← Back
                  </button>
                ) : <span />}
                <button
                  className="btn btn-primary"
                  onClick={next}
                  disabled={!canNext()}
                  style={{ opacity: canNext() ? 1 : 0.4, cursor: canNext() ? "pointer" : "not-allowed" }}
                >
                  {step === 3 ? "Submit request" : "Continue"} <HCIcon name="arrow" />
                </button>
              </div>
            </>
          )}
        </div>
      </div>
    </ModalShell>
  );
};

Object.assign(window, { HCModals: { DoctorModal, ConsentModal, BookingModal } });
