/* Consult booking — mock flow.
 * Date → time → contact form → confirmation. Reads stack context from
 * sessionStorage if user came from BioReveal, otherwise renders generic.
 * No real backend; submission stays client-side and shows a confirmation.
 */

const TIMES = [
  { t: "9:00 AM", taken: false },
  { t: "10:30 AM", taken: false },
  { t: "12:00 PM", taken: true },
  { t: "1:30 PM", taken: false },
  { t: "3:00 PM", taken: false },
  { t: "4:30 PM", taken: true },
  { t: "6:00 PM", taken: false },
];

const CLINICIANS = [
  { name: "Dr. Maya Brennan, MD", cred: "Internal Medicine · Functional Med fellow", years: 11, photo: null, color: "#10b981" },
  { name: "Dr. Jonas Reid, DO", cred: "Sports Medicine · Endocrine focus", years: 9, photo: null, color: "#6366f1" },
  { name: "Dr. Tara Olamide, MD", cred: "Anti-aging · Hormone optimization", years: 14, photo: null, color: "#f59e0b" },
];

function getNextDays(n) {
  const days = [];
  const now = new Date();
  for (let i = 1; i <= n; i++) {
    const d = new Date(now);
    d.setDate(now.getDate() + i);
    days.push(d);
  }
  return days;
}

function fmtDay(d) {
  return d.toLocaleDateString("en-US", { weekday: "short" }).toUpperCase();
}
function fmtNum(d) {
  return d.getDate();
}
function fmtMonth(d) {
  return d.toLocaleDateString("en-US", { month: "short" }).toUpperCase();
}
function fmtFull(d) {
  return d.toLocaleDateString("en-US", { weekday: "long", month: "long", day: "numeric" });
}

const ConsultPage = () => {
  const Header = window.Header;
  const Footer = window.Footer;
  const days = React.useMemo(() => getNextDays(10), []);
  const [step, setStep] = React.useState("schedule"); // schedule | form | done
  const [selectedDay, setSelectedDay] = React.useState(days[0]);
  const [selectedTime, setSelectedTime] = React.useState(null);
  const [clinician, setClinician] = React.useState(CLINICIANS[0]);
  const [form, setForm] = React.useState({ name: "", email: "", phone: "", note: "" });
  const [errors, setErrors] = React.useState({});

  // Pull BioReveal context if it exists
  const stackCtx = React.useMemo(() => {
    try {
      const raw = sessionStorage.getItem("br_protocol_summary");
      return raw ? JSON.parse(raw) : null;
    } catch { return null; }
  }, []);

  function pickTime(t) {
    setSelectedTime(t);
    setStep("form");
    window.scrollTo({ top: 0, behavior: "smooth" });
  }

  function submit(e) {
    e.preventDefault();
    const errs = {};
    if (!form.name.trim()) errs.name = "Required";
    if (!/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(form.email)) errs.email = "Valid email required";
    if (!form.phone.trim() || form.phone.replace(/\D/g, "").length < 10) errs.phone = "10-digit phone required";
    setErrors(errs);
    if (Object.keys(errs).length) return;
    setStep("done");
    window.scrollTo({ top: 0, behavior: "smooth" });
  }

  return (
    <div className="br-page" style={{ background: "var(--paper)" }}>
      <Header active="bioreveal"/>

      {/* HERO */}
      <section className="br-section" style={{ paddingTop: 56, paddingBottom: 24 }}>
        <div className="container" style={{ maxWidth: 920 }}>
          <div className="eyebrow" style={{ marginBottom: 14 }}>★ THE NEXT STEP</div>
          <h1 style={{ fontFamily: "var(--font-display)", fontWeight: 800, fontSize: "clamp(36px, 6vw, 64px)", letterSpacing: "-0.025em", lineHeight: 1.05, margin: 0 }}>
            {step === "done" ? "You're booked." : "Book your $0 MD consult."}
          </h1>
          <p style={{ fontSize: 18, color: "var(--muted)", marginTop: 16, maxWidth: 640, lineHeight: 1.55 }}>
            {step === "done"
              ? `We sent a confirmation to ${form.email}. ${clinician.name.split(",")[0]} will join you ${fmtFull(selectedDay)} at ${selectedTime}.`
              : "20 minutes with a licensed U.S. clinician. They review your protocol, ask about your history, and either approve, adjust, or pause before anything ships. Free — no card required."}
          </p>
        </div>
      </section>

      {/* STACK SUMMARY (if from BioReveal) */}
      {stackCtx && step !== "done" && (
        <section className="br-section" style={{ paddingTop: 0, paddingBottom: 28 }}>
          <div className="container" style={{ maxWidth: 920 }}>
            <div style={{ background: "var(--paper-2)", border: "1px solid var(--paper-3)", borderRadius: 12, padding: "20px 24px", display: "flex", flexWrap: "wrap", alignItems: "center", justifyContent: "space-between", gap: 16 }}>
              <div>
                <div style={{ fontFamily: "var(--font-mono)", fontSize: 11, letterSpacing: "0.18em", color: "var(--muted)", textTransform: "uppercase", marginBottom: 6 }}>Reviewing on this consult</div>
                <div style={{ fontFamily: "var(--font-display)", fontWeight: 700, fontSize: 22 }}>{stackCtx.stackName || "Your BioReveal stack"}</div>
                {stackCtx.peptides && stackCtx.peptides.length > 0 && (
                  <div style={{ marginTop: 8, fontSize: 14, color: "var(--ink)", opacity: 0.75 }}>
                    {stackCtx.peptides.join(" · ")}
                  </div>
                )}
              </div>
              {stackCtx.total && (
                <div style={{ textAlign: "right" }}>
                  <div style={{ fontFamily: "var(--font-mono)", fontSize: 10, letterSpacing: "0.18em", color: "var(--muted)" }}>EST. STACK</div>
                  <div style={{ fontFamily: "var(--font-display)", fontWeight: 800, fontSize: 28 }}>${stackCtx.total}<span style={{ fontSize: 14, fontWeight: 600, opacity: 0.6 }}>/mo</span></div>
                </div>
              )}
            </div>
          </div>
        </section>
      )}

      {/* STEP: SCHEDULE */}
      {step === "schedule" && (
        <>
          {/* Clinician picker */}
          <section className="br-section" style={{ paddingTop: 16, paddingBottom: 24 }}>
            <div className="container" style={{ maxWidth: 920 }}>
              <div className="eyebrow" style={{ marginBottom: 14 }}>★ CHOOSE A CLINICIAN</div>
              <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(240px, 1fr))", gap: 12 }}>
                {CLINICIANS.map(c => (
                  <button key={c.name} onClick={() => setClinician(c)}
                    style={{
                      textAlign: "left", padding: "16px 18px", borderRadius: 12, cursor: "pointer",
                      background: clinician.name === c.name ? "var(--ink)" : "var(--paper-2)",
                      color: clinician.name === c.name ? "var(--paper)" : "var(--ink)",
                      border: clinician.name === c.name ? "1px solid var(--ink)" : "1px solid var(--paper-3)",
                      transition: "all 0.15s",
                    }}>
                    <div style={{ display: "flex", alignItems: "center", gap: 12, marginBottom: 8 }}>
                      <div style={{ width: 40, height: 40, borderRadius: "50%", background: c.color, color: "#fff", display: "flex", alignItems: "center", justifyContent: "center", fontFamily: "var(--font-display)", fontWeight: 800, fontSize: 16, flexShrink: 0 }}>
                        {c.name.split(" ")[1][0]}{c.name.split(" ")[2] ? c.name.split(" ")[2][0] : ""}
                      </div>
                      <div style={{ fontFamily: "var(--font-display)", fontWeight: 700, fontSize: 15, lineHeight: 1.2 }}>{c.name}</div>
                    </div>
                    <div style={{ fontSize: 12, opacity: 0.75, lineHeight: 1.4 }}>{c.cred}</div>
                    <div style={{ fontFamily: "var(--font-mono)", fontSize: 10, letterSpacing: "0.16em", textTransform: "uppercase", marginTop: 8, opacity: 0.6 }}>{c.years} yrs practicing</div>
                  </button>
                ))}
              </div>
            </div>
          </section>

          {/* Date picker */}
          <section className="br-section" style={{ paddingTop: 16, paddingBottom: 16 }}>
            <div className="container" style={{ maxWidth: 920 }}>
              <div className="eyebrow" style={{ marginBottom: 14 }}>★ PICK A DAY</div>
              <div style={{ display: "flex", gap: 8, overflowX: "auto", paddingBottom: 8 }}>
                {days.map((d, i) => {
                  const isSel = d.toDateString() === selectedDay.toDateString();
                  return (
                    <button key={i} onClick={() => setSelectedDay(d)}
                      style={{
                        flex: "0 0 auto", padding: "14px 18px", borderRadius: 10, cursor: "pointer",
                        background: isSel ? "var(--ink)" : "var(--paper-2)",
                        color: isSel ? "var(--paper)" : "var(--ink)",
                        border: isSel ? "1px solid var(--ink)" : "1px solid var(--paper-3)",
                        minWidth: 86, textAlign: "center", transition: "all 0.15s",
                      }}>
                      <div style={{ fontFamily: "var(--font-mono)", fontSize: 10, letterSpacing: "0.18em", opacity: 0.7 }}>{fmtDay(d)}</div>
                      <div style={{ fontFamily: "var(--font-display)", fontWeight: 800, fontSize: 26, lineHeight: 1.1, marginTop: 4 }}>{fmtNum(d)}</div>
                      <div style={{ fontFamily: "var(--font-mono)", fontSize: 10, letterSpacing: "0.18em", opacity: 0.7, marginTop: 2 }}>{fmtMonth(d)}</div>
                    </button>
                  );
                })}
              </div>
            </div>
          </section>

          {/* Time slots */}
          <section className="br-section" style={{ paddingTop: 16, paddingBottom: 56 }}>
            <div className="container" style={{ maxWidth: 920 }}>
              <div className="eyebrow" style={{ marginBottom: 14 }}>★ AVAILABLE TIMES — {fmtFull(selectedDay).toUpperCase()}</div>
              <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fill, minmax(140px, 1fr))", gap: 10 }}>
                {TIMES.map(s => (
                  <button key={s.t} disabled={s.taken} onClick={() => pickTime(s.t)}
                    style={{
                      padding: "16px 14px", borderRadius: 10,
                      background: s.taken ? "var(--paper-2)" : "var(--paper)",
                      color: s.taken ? "var(--muted)" : "var(--ink)",
                      border: s.taken ? "1px solid var(--paper-3)" : "1.5px solid var(--ink)",
                      cursor: s.taken ? "not-allowed" : "pointer",
                      fontFamily: "var(--font-display)", fontWeight: 700, fontSize: 15,
                      textDecoration: s.taken ? "line-through" : "none",
                      opacity: s.taken ? 0.5 : 1,
                      transition: "all 0.12s",
                    }}
                    onMouseEnter={(e) => { if (!s.taken) { e.currentTarget.style.background = "var(--ink)"; e.currentTarget.style.color = "var(--paper)"; } }}
                    onMouseLeave={(e) => { if (!s.taken) { e.currentTarget.style.background = "var(--paper)"; e.currentTarget.style.color = "var(--ink)"; } }}>
                    {s.t}
                    {s.taken && <div style={{ fontFamily: "var(--font-mono)", fontSize: 9, letterSpacing: "0.15em", marginTop: 4, opacity: 0.7 }}>BOOKED</div>}
                  </button>
                ))}
              </div>
            </div>
          </section>
        </>
      )}

      {/* STEP: FORM */}
      {step === "form" && (
        <section className="br-section" style={{ paddingTop: 16, paddingBottom: 80 }}>
          <div className="container" style={{ maxWidth: 640 }}>
            <div style={{ background: "var(--paper-2)", border: "1px solid var(--paper-3)", borderRadius: 12, padding: "20px 24px", marginBottom: 28, display: "flex", justifyContent: "space-between", alignItems: "center", flexWrap: "wrap", gap: 12 }}>
              <div>
                <div style={{ fontFamily: "var(--font-mono)", fontSize: 11, letterSpacing: "0.18em", color: "var(--muted)", textTransform: "uppercase", marginBottom: 6 }}>Confirming</div>
                <div style={{ fontFamily: "var(--font-display)", fontWeight: 700, fontSize: 18 }}>{clinician.name.split(",")[0]} · {fmtFull(selectedDay)} · {selectedTime}</div>
              </div>
              <button onClick={() => setStep("schedule")} style={{ background: "none", border: "none", color: "var(--ink)", fontFamily: "var(--font-mono)", fontSize: 11, letterSpacing: "0.18em", textTransform: "uppercase", cursor: "pointer", textDecoration: "underline", textUnderlineOffset: 4 }}>← Change</button>
            </div>

            <div className="eyebrow" style={{ marginBottom: 14 }}>★ YOUR DETAILS</div>
            <form onSubmit={submit} style={{ display: "grid", gap: 16 }}>
              <Field label="Full name" error={errors.name}>
                <input value={form.name} onChange={e => setForm({...form, name: e.target.value})} placeholder="Jane Doe" />
              </Field>
              <Field label="Email" error={errors.email}>
                <input type="email" value={form.email} onChange={e => setForm({...form, email: e.target.value})} placeholder="you@email.com" />
              </Field>
              <Field label="Mobile" error={errors.phone}>
                <input type="tel" value={form.phone} onChange={e => setForm({...form, phone: e.target.value})} placeholder="(555) 123-4567" />
              </Field>
              <Field label="Anything you want them to know? (optional)">
                <textarea value={form.note} onChange={e => setForm({...form, note: e.target.value})} rows={3} placeholder="Allergies, current meds, specific questions about your protocol…" />
              </Field>
              <div style={{ marginTop: 8 }}>
                <button type="submit" className="btn btn-dark btn-lg" style={{ width: "100%" }}>Confirm consult →</button>
                <p style={{ fontSize: 12, color: "var(--muted)", marginTop: 12, lineHeight: 1.5, textAlign: "center" }}>
                  No charge for the consult. Your card is only billed if you approve a protocol after the call.
                </p>
              </div>
            </form>
          </div>
        </section>
      )}

      {/* STEP: DONE */}
      {step === "done" && (
        <section className="br-section" style={{ paddingTop: 16, paddingBottom: 96 }}>
          <div className="container" style={{ maxWidth: 720 }}>
            <div style={{ background: "var(--ink)", color: "var(--paper)", borderRadius: 14, padding: "36px 32px" }}>
              <div className="eyebrow" style={{ color: "#888", marginBottom: 18 }}>★ CONFIRMATION</div>
              <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 28, marginBottom: 28 }}>
                <div>
                  <div style={{ fontFamily: "var(--font-mono)", fontSize: 10, letterSpacing: "0.18em", opacity: 0.6, marginBottom: 6 }}>WHEN</div>
                  <div style={{ fontFamily: "var(--font-display)", fontWeight: 700, fontSize: 18, lineHeight: 1.3 }}>{fmtFull(selectedDay)}<br/>{selectedTime} EST</div>
                </div>
                <div>
                  <div style={{ fontFamily: "var(--font-mono)", fontSize: 10, letterSpacing: "0.18em", opacity: 0.6, marginBottom: 6 }}>WITH</div>
                  <div style={{ fontFamily: "var(--font-display)", fontWeight: 700, fontSize: 18, lineHeight: 1.3 }}>{clinician.name}<br/><span style={{ fontSize: 13, opacity: 0.7, fontWeight: 500 }}>{clinician.cred}</span></div>
                </div>
              </div>
              <div style={{ borderTop: "1px solid #333", paddingTop: 24, fontSize: 14, lineHeight: 1.6, opacity: 0.85 }}>
                <p style={{ margin: 0 }}>
                  <strong style={{ color: "var(--paper)" }}>Confirmation sent</strong> to {form.email}. We'll text {form.phone} a reminder 1 hour before. The link to join (Zoom) is in your email.
                </p>
                <p style={{ marginTop: 12, marginBottom: 0 }}>
                  Before the call: nothing required. The clinician already has your BioReveal intake. They'll spend the time on questions, not setup.
                </p>
              </div>
            </div>

            <div style={{ display: "flex", gap: 12, justifyContent: "center", marginTop: 36, flexWrap: "wrap" }}>
              <a href="/" className="btn btn-dark btn-lg">← Back to home</a>
              <a href="/learn.html" className="btn btn-ghost btn-lg">Learn more about peptides</a>
            </div>
          </div>
        </section>
      )}

      <Footer/>
    </div>
  );
};

const Field = ({ label, error, children }) => (
  <label style={{ display: "block" }}>
    <div style={{ fontFamily: "var(--font-mono)", fontSize: 11, letterSpacing: "0.18em", color: error ? "#ef4444" : "var(--muted)", textTransform: "uppercase", marginBottom: 8 }}>
      {label} {error && <span style={{ marginLeft: 8 }}>· {error}</span>}
    </div>
    {React.cloneElement(children, {
      style: {
        width: "100%", padding: "14px 16px", borderRadius: 10,
        border: error ? "1.5px solid #ef4444" : "1.5px solid var(--paper-3)",
        background: "var(--paper)", fontFamily: "var(--font-display)", fontSize: 15,
        color: "var(--ink)", outline: "none", transition: "border-color 0.15s",
        ...(children.props.style || {}),
      },
      onFocus: (e) => { if (!error) e.target.style.borderColor = "var(--ink)"; },
      onBlur: (e) => { if (!error) e.target.style.borderColor = "var(--paper-3)"; },
    })}
  </label>
);

ReactDOM.createRoot(document.getElementById("root")).render(<ConsultPage/>);
