/* ============================================================
   NEUROMED — Multi-step booking form
   ============================================================ */
const { useState: useStateB } = React;

const REASONS = [
  { id: "consulta", label: "Primera consulta", hint: "Evaluación clínica inicial" },
  { id: "segunda", label: "Segunda opinión", hint: "Revisar diagnóstico existente" },
  { id: "post", label: "Control postoperatorio", hint: "Seguimiento de cirugía previa" },
  { id: "urgencia", label: "Urgencia derivada", hint: "Canal prioritario · 24 hs" },
];

const COVERAGES = ["Galeno", "IOMA", "Medicus", "OSDE", "OSRJA", "Swiss Medical", "Particular", "Otra obra social"];

/* Cada sede enruta a la secretaría correspondiente (email + WhatsApp) */
const SEDES = [
  { id: "buenpastor", label: "Clínica del Buen Pastor", addr: "Av. Gral. Enrique Mosconi 1716 · Lomas del Mirador",
    email: "turnos.buenpastor@neuromed.ar", wa: "5491158136779" },
  { id: "alcorta", label: "Clínica Privada Alcorta", addr: "Aristóbulo del Valle 2629 · Moreno",
    email: "turnos.alcorta@neuromed.ar", wa: "5491158136779" },
  { id: "particular", label: "Consultorio particular", addr: "Consultorio privado · CABA",
    email: "turnos@neuromed.ar", wa: "5491158136779" },
];

function BookingModal({ open, onClose, initialStep = 1, initialData }) {
  const [step, setStep] = useStateB(initialStep);
  const [data, setData] = useStateB(initialData || {
    reason: "consulta",
    coverage: "",
    sede: "",
    name: "",
    email: "",
    phone: "",
    notes: "",
  });

  const [sending, setSending] = useStateB(false);
  const [sendError, setSendError] = useStateB(false);

  if (!open) return null;
  const set = (k, v) => setData((d) => ({ ...d, [k]: v }));
  const totalSteps = 3;
  const progress = (step / totalSteps) * 100;

  const sedeObj = SEDES.find((s) => s.id === data.sede);

  const canNext = {
    1: !!data.reason && !!data.coverage && !!data.sede,
    2: !!data.name && !!data.email && !!data.phone,
    3: true,
  }[step];

  const submit = async () => {
    setSending(true);
    setSendError(false);
    try {
      const res  = await fetch('send.php', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(data),
      });
      const json = await res.json();
      if (json.ok) { setStep(4); } else { setSendError(true); }
    } catch { setSendError(true); }
    finally { setSending(false); }
  };

  return (
    <div className="modal-backdrop" onClick={onClose}>
      <div className="modal" onClick={(e) => e.stopPropagation()}>
        <button className="modal-close" onClick={onClose} aria-label="Cerrar">
          <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6"><path d="M6 6l12 12M18 6L6 18"/></svg>
        </button>

        <div className="modal-grid">
          <aside className="modal-aside">
            <div style={{ marginBottom: 36 }}>
              <img src="logo.png" alt="Neuromed" style={{ height: 40, width: "auto", display: "block" }} />
            </div>
            <p className="mono" style={{ color: "var(--nm-navy-500)", marginBottom: 20, letterSpacing: "0.1em" }}>Pedido de turno</p>
            <h3 className="serif" style={{ fontSize: 30, lineHeight: 1.1, fontWeight: 400, margin: "0 0 18px", letterSpacing: "-0.02em", color: "var(--nm-navy)" }}>
              Cuatro pasos. Tres minutos. Sin formularios eternos.
            </h3>
            <ol className="step-list">
              {["Motivo, cobertura y sede", "Tus datos", "Confirmación"].map((label, i) => (
                <li key={i} className={"step-item" + (step === i + 1 ? " current" : step > i + 1 ? " done" : "")}>
                  <span className="step-dot">{step > i + 1 ? <Icon.Check size={12} /> : i + 1}</span>
                  <span>{label}</span>
                </li>
              ))}
            </ol>

            <div className="aside-footer mono">
              <div>info@neuromed.ar</div>
            </div>
          </aside>

          <div className="form-card modal-form" style={{ border: 0, background: "transparent", borderRadius: 0, minHeight: 0 }}>
            {step < 4 && (
              <div className="form-progress">
                <span>0{step} / 0{totalSteps}</span>
                <div className="bar" style={{ "--p": `${progress}%` }} />
                <span>{Math.round(progress)}%</span>
              </div>
            )}

            {step === 1 && (
              <>
                <h3 className="step-title serif">¿Por qué nos consultás?</h3>
                <p className="step-desc">Elegí la opción que mejor describa tu situación. Después confirmamos detalles por teléfono.</p>
                <div className="choices" style={{ marginBottom: 24 }}>
                  {REASONS.map((r) => (
                    <button key={r.id} className={"choice" + (data.reason === r.id ? " selected" : "")} onClick={() => set("reason", r.id)}>
                      <span className="ck" />
                      <span className="label">{r.label}</span>
                      <span className="hint">{r.hint}</span>
                    </button>
                  ))}
                </div>

                <div className="field">
                  <label>Cobertura</label>
                  <select value={data.coverage} onChange={(e) => set("coverage", e.target.value)}>
                    <option value="">Seleccioná tu cobertura…</option>
                    {COVERAGES.map((c) => <option key={c} value={c}>{c}</option>)}
                  </select>
                </div>

                <div className="field" style={{ marginTop: 18 }}>
                  <label>Sede</label>
                  <div className="choices">
                    {SEDES.map((s) => (
                      <button key={s.id} className={"choice" + (data.sede === s.id ? " selected" : "")} onClick={() => set("sede", s.id)}>
                        <span className="ck" />
                        <span className="label">{s.label}</span>
                        <span className="hint">{s.addr}</span>
                      </button>
                    ))}
                  </div>
                </div>
              </>
            )}

            {step === 2 && (
              <>
                <h3 className="step-title serif">Tus datos</h3>
                <p className="step-desc">Solo lo imprescindible. Nada de spam, nada de listas.</p>
                <div className="field">
                  <label>Nombre y apellido</label>
                  <input value={data.name} onChange={(e) => set("name", e.target.value)} placeholder="María Pérez" />
                </div>
                <div className="field-row" style={{ marginTop: 18 }}>
                  <div className="field" style={{ marginTop: 0 }}>
                    <label>Email</label>
                    <input type="email" value={data.email} onChange={(e) => set("email", e.target.value)} placeholder="vos@email.com" />
                  </div>
                  <div className="field" style={{ marginTop: 0 }}>
                    <label>Teléfono</label>
                    <input value={data.phone} onChange={(e) => set("phone", e.target.value)} placeholder="+54 11…" />
                  </div>
                </div>
                <div className="field">
                  <label>Algo que debamos saber (opcional)</label>
                  <textarea rows="3" value={data.notes} onChange={(e) => set("notes", e.target.value)} placeholder="Síntomas, derivación, estudios previos…" />
                </div>
              </>
            )}

            {step === 3 && (
              <>
                <h3 className="step-title serif">Confirmá tu solicitud</h3>
                <p className="step-desc">Tu pedido llega a la secretaría de la sede elegida por email, y se abre WhatsApp para enviarlo también por ese canal. Te respondemos en menos de 24 hs hábiles.</p>
                <div className="summary">
                  <div className="summary-row"><span className="k">Motivo</span><span className="v">{REASONS.find(r => r.id === data.reason)?.label}</span></div>
                  <div className="summary-row"><span className="k">Cobertura</span><span className="v">{data.coverage || "—"}</span></div>
                  <div className="summary-row"><span className="k">Sede</span><span className="v">{sedeObj?.label}</span></div>
                  <div className="summary-row"><span className="k">Paciente</span><span className="v">{data.name}</span></div>
                  <div className="summary-row"><span className="k">Email</span><span className="v">{data.email}</span></div>
                  <div className="summary-row"><span className="k">Teléfono</span><span className="v">{data.phone}</span></div>
                  <div className="summary-row"><span className="k">Se envía a</span><span className="v">{sedeObj?.email}</span></div>
                </div>
              </>
            )}

            {step === 4 && (
              <div className="confirmed">
                <div className="check"><Icon.Check /></div>
                <h4 className="serif">¡Solicitud enviada!</h4>
                <p>Gracias, {data.name.split(" ")[0] || ""}. Recibimos tu pedido para <b>{sedeObj?.label}</b>. Te contactaremos a la brevedad, dentro de las <b>48/72 hs hábiles</b>.</p>
                <button className="btn btn-ghost" onClick={onClose}>Cerrar</button>
              </div>
            )}

            {step < 4 && (
              <>
                {sendError && (
                  <p style={{ color: "#c0392b", fontSize: 13, margin: "12px 0 0", textAlign: "right" }}>
                    No se pudo enviar. Intentá de nuevo o escribinos por WhatsApp.
                  </p>
                )}
                <div className="form-actions">
                  {step > 1 ? (
                    <button className="btn btn-ghost" onClick={() => setStep(step - 1)}>
                      <Icon.Chev dir="left" /> Atrás
                    </button>
                  ) : <span />}

                  <button className="btn" disabled={!canNext || sending}
                          style={{ opacity: (canNext && !sending) ? 1 : 0.4, cursor: (canNext && !sending) ? "pointer" : "not-allowed" }}
                          onClick={() => { if (!canNext || sending) return; step === 3 ? submit() : setStep(step + 1); }}>
                    {step === 3 ? (sending ? "Enviando…" : "Enviar solicitud") : "Continuar"} <Icon.Arrow />
                  </button>
                </div>
              </>
            )}
          </div>
        </div>
      </div>
    </div>
  );
}

function BookingInline({ onBook, onContinue }) {
  return (
    <section className="section" id="turnos" style={{ background: "var(--paper)" }}>
      <div className="container">
        <div className="section-head">
          <div className="section-num">
            <span className="index mono">§ 09</span>
            <span className="label mono">Pedir turno</span>
          </div>
          <h2 className="section-title serif">
            Reservá tu lugar en <em>tres minutos</em>.
          </h2>
        </div>

        <div className="booking">
          <div className="booking-info">
            <h3 className="serif">
              Hablás con humanos. Pedís en minutos. Respuesta a la brevedad.
            </h3>
            <p>
              Confirmamos tu turno en menos de 48/72 hs hábiles.
            </p>

            <div className="contact-card">
              <div className="contact-row">
                <span className="k">Email</span>
                <span className="v"><a href="mailto:info@neuromed.ar">info@neuromed.ar</a></span>
              </div>
              <div className="contact-row">
                <span className="k">WhatsApp</span>
                <span className="v"><a href="https://wa.me/5491158136779" target="_blank" rel="noreferrer">+54 9 11 5813 6779</a></span>
              </div>
              <div className="contact-row">
                <span className="k">Horarios</span>
                <span className="v">Lun a Vie · 09 a 18 hs</span>
              </div>
            </div>

            <button className="btn" style={{ marginTop: 28 }} onClick={onBook}>
              Abrir formulario de turno <Icon.Arrow />
            </button>
          </div>

          <BookingPreview onContinue={onContinue} />
        </div>
      </div>
    </section>
  );
}

function BookingPreview({ onContinue }) {
  const [reason, setReason] = useStateB("consulta");
  const [coverage, setCoverage] = useStateB("");
  const [sede, setSede] = useStateB("");
  const canGo = !!reason && !!coverage && !!sede;
  const go = () => {
    if (!canGo) return;
    onContinue({ reason, coverage, sede, name: "", email: "", phone: "", notes: "" });
  };
  return (
    <div className="form-card form-card-preview">
      <div className="form-progress">
        <span>01 / 03</span>
        <div className="bar" style={{ "--p": "33%" }} />
        <span>33%</span>
      </div>
      <h3 className="step-title serif">¿Por qué nos consultás?</h3>
      <p className="step-desc">Elegí la opción que mejor describa tu situación.</p>
      <div className="field">
        <label>Motivo de consulta</label>
        <select value={reason} onChange={(e) => setReason(e.target.value)}>
          {REASONS.map((r) => <option key={r.id} value={r.id}>{r.label}</option>)}
        </select>
      </div>
      <div className="field" style={{ marginTop: 14 }}>
        <label>Cobertura</label>
        <select value={coverage} onChange={(e) => setCoverage(e.target.value)}>
          <option value="">Seleccioná tu cobertura…</option>
          {COVERAGES.map((c) => <option key={c} value={c}>{c}</option>)}
        </select>
      </div>
      <div className="field" style={{ marginTop: 14 }}>
        <label>Sede</label>
        <select value={sede} onChange={(e) => setSede(e.target.value)}>
          <option value="">Seleccioná una sede…</option>
          {SEDES.map((s) => <option key={s.id} value={s.id}>{s.label}</option>)}
        </select>
      </div>
      <div className="form-actions">
        <span />
        <button className="btn" disabled={!canGo}
                style={{ opacity: canGo ? 1 : 0.4, cursor: canGo ? "pointer" : "not-allowed" }}
                onClick={go}>
          Continuar <Icon.Arrow />
        </button>
      </div>
    </div>
  );
}

Object.assign(window, { BookingModal, BookingInline });
