// Wasabil — Agenda una reunión
const { useState: useStateAgenda, useEffect: useEffectAgenda } = React;

// ---- CONFIG ----
// Cuando tengas tu cuenta de Calendly lista, pega acá tu URL (ej: "https://calendly.com/wasabil/demo")
// y el widget real reemplazará el mockup del paso 1 automáticamente.
// Deja "" para seguir con el flujo mockup que diseñamos.
const CALENDLY_URL = /*EDITMODE-BEGIN*/{
  "calendlyUrl": "https://calendly.com/hola-wasabil/demo-wasabil-45-min",
  "showLiveWidget": true
}/*EDITMODE-END*/;

function CalendlyEmbed({ url, onBooked }) {
  useEffectAgenda(() => {
    if (!document.querySelector('script[src*="calendly.com/assets/external/widget.js"]')) {
      const s = document.createElement('script');
      s.src = "https://assets.calendly.com/assets/external/widget.js";
      s.async = true;
      document.body.appendChild(s);
    }
    const handler = (e) => {
      if (e.data && e.data.event === 'calendly.event_scheduled') {
        onBooked && onBooked(e.data.payload);
      }
    };
    window.addEventListener('message', handler);
    return () => window.removeEventListener('message', handler);
  }, []);
  return (
    <>
      <link href="https://assets.calendly.com/assets/external/widget.css" rel="stylesheet" />
      <div
        className="calendly-inline-widget"
        data-url={`${url}?hide_gdpr_banner=1&hide_event_type_details=1&primary_color=5c8a3c&text_color=141311&background_color=fbf9f3`}
        style={{ minWidth: 320, height: 660, background: "var(--paper)" }}
      />
    </>
  );
}

function AgendaPage() {
  const useLive = CALENDLY_URL.showLiveWidget && CALENDLY_URL.calendlyUrl;
  const [booked, setBooked] = useStateAgenda(false);
  const [invitee, setInvitee] = useStateAgenda(null);

  const handleBooked = (payload) => {
    setInvitee(payload?.invitee || null);
    setBooked(true);
  };

  const [step, setStep] = useStateAgenda(0); // 0=pick, 1=form, 2=done
  const [selectedDate, setSelectedDate] = useStateAgenda(null);
  const [selectedTime, setSelectedTime] = useStateAgenda(null);
  const [form, setForm] = useStateAgenda({ name: "", email: "", company: "", docs: "", msg: "" });

  // Calendar generation — current month
  const today = new Date();
  const year = today.getFullYear();
  const month = today.getMonth();
  const daysInMonth = new Date(year, month + 1, 0).getDate();
  const firstDay = new Date(year, month, 1).getDay(); // 0 = Sun
  const mondayFirst = firstDay === 0 ? 6 : firstDay - 1;
  const cells = [];
  for (let i = 0; i < mondayFirst; i++) cells.push(null);
  for (let d = 1; d <= daysInMonth; d++) {
    const dt = new Date(year, month, d);
    const isPast = dt < new Date(today.getFullYear(), today.getMonth(), today.getDate());
    const isWeekend = dt.getDay() === 0 || dt.getDay() === 6;
    cells.push({ d, dt, available: !isPast && !isWeekend });
  }

  const monthName = today.toLocaleDateString("es-CL", { month: "long", year: "numeric" });

  const times = ["09:00", "10:00", "11:00", "12:00", "14:00", "15:00", "16:00", "17:00"];

  const pick = (c) => {
    if (!c || !c.available) return;
    setSelectedDate(c);
  };

  const confirm = () => {
    if (selectedDate && selectedTime) setStep(1);
  };

  const submit = (e) => {
    e.preventDefault();
    setStep(2);
  };

  const fmt = (dt) => dt.toLocaleDateString("es-CL", { weekday: "long", day: "numeric", month: "long" });

  return (
    <>
      <Nav current="agenda" />
      <section style={{ padding: "72px 0 48px", borderBottom: "1px solid var(--rule)" }}>
        <div className="container-wide">
          <div style={{ display: "grid", gridTemplateColumns: "0.8fr 1.2fr", gap: 72, alignItems: "start" }}>
            {/* LEFT — context */}
            <div style={{ position: "sticky", top: 96 }}>
              <div className="eyebrow"><span className="dot"/>Demo · 45 min</div>
              <h1 className="display-2 serif" style={{ marginTop: 16 }}>
                Vamos a <em className="italic">mostrarte</em> cómo Wasabil se adapta a tu negocio.
              </h1>
              <p className="lede" style={{ marginTop: 20, fontSize: 18 }}>
                Una llamada de 45 minutos con alguien del equipo. Sin venta dura — te mostramos cómo funciona, resolvemos dudas y decides tú.
              </p>

              <div style={{ marginTop: 40, padding: 24, background: "var(--paper)", border: "1px solid var(--rule)", borderRadius: 12, display: "flex", flexDirection: "column", gap: 16 }}>
                {[
                  { k: "Duración", v: "45 minutos" },
                  { k: "Dónde", v: "Google Meet · link por email" },
                  { k: "Idioma", v: "Español" },
                  { k: "Quién", v: "Equipo de producto" },
                ].map((row, i) => (
                  <div key={i} style={{ display: "grid", gridTemplateColumns: "100px 1fr", gap: 16, alignItems: "baseline" }}>
                    <span className="caption">{row.k}</span>
                    <span style={{ fontSize: 14, color: "var(--ink)" }}>{row.v}</span>
                  </div>
                ))}
              </div>

              <div style={{ marginTop: 32 }}>
                <div className="caption" style={{ marginBottom: 16 }}>En la llamada vemos</div>
                <ul style={{ listStyle: "none", padding: 0, margin: 0, display: "flex", flexDirection: "column", gap: 10 }}>
                  {[
                    "Cómo conectar tu eCommerce en 10 minutos",
                    "Cuánto IVA extranjero podrías recuperar hoy",
                    "Demo del MCP conectado a Claude",
                    "Integración con tu contador o facturador actual",
                  ].map((it, i) => (
                    <li key={i} style={{ display: "flex", alignItems: "flex-start", gap: 12, fontSize: 14, color: "var(--ink-2)" }}>
                      <svg width="14" height="14" viewBox="0 0 24 24" fill="none" style={{ marginTop: 4, flexShrink: 0 }}><path d="M5 12l5 5L20 7" stroke="oklch(0.55 0.18 135)" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round"/></svg>
                      {it}
                    </li>
                  ))}
                </ul>
              </div>
            </div>

            {/* RIGHT — booking widget */}
            <div className="window" style={{ overflow: "hidden" }}>
              <div className="window-bar">
                <div className="window-dots"><span/><span/><span/></div>
                <div className="window-title">Agendar reunión · Wasabil</div>
                <span className="pill" style={{ fontSize: 10, padding: "3px 8px", background: "var(--accent-wash)", color: "oklch(0.35 0.1 135)", border: "1px solid transparent" }}>45 min</span>
              </div>

              {useLive && !booked && (
                <CalendlyEmbed url={CALENDLY_URL.calendlyUrl} onBooked={handleBooked} />
              )}

              {useLive && booked && (
                <div style={{ padding: "72px 48px", background: "var(--paper)", textAlign: "center", position: "relative" }}>
                  <div style={{ position: "absolute", top: 24, right: 28, opacity: 0.9 }}>
                    <Mascot pose="clap" size={80} />
                  </div>
                  <div style={{ width: 64, height: 64, borderRadius: "50%", background: "oklch(0.55 0.18 135)", display: "grid", placeItems: "center", margin: "0 auto 28px" }}>
                    <svg width="32" height="32" viewBox="0 0 24 24" fill="none"><path d="M5 12l5 5L20 7" stroke="#0a0a0a" strokeWidth="3" strokeLinecap="round" strokeLinejoin="round"/></svg>
                  </div>
                  <h3 className="display-3 serif" style={{ marginBottom: 14 }}>
                    ¡Listo{invitee?.name ? `, ${invitee.name.split(" ")[0]}` : ""}!
                  </h3>
                  <p style={{ color: "var(--ink-2)", fontSize: 16, maxWidth: "38ch", margin: "0 auto 32px", lineHeight: 1.6 }}>
                    Te enviamos una invitación{invitee?.email ? <> a <strong>{invitee.email}</strong></> : ""} con el link de Google Meet y todos los detalles.
                  </p>
                  <div style={{ marginTop: 8, display: "flex", gap: 10, justifyContent: "center" }}>
                    <a className="btn btn-ghost" href="index.html">Volver al inicio</a>
                    <a className="btn btn-primary" href="producto.html">Explorar producto</a>
                  </div>
                </div>
              )}

              {!useLive && (
                <>

              {step === 0 && (
                <div style={{ padding: 32, background: "var(--paper)" }}>
                  <div style={{ display: "grid", gridTemplateColumns: "1.1fr 0.9fr", gap: 32 }}>
                    {/* Calendar */}
                    <div>
                      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 20 }}>
                        <h3 className="serif" style={{ fontSize: 20, textTransform: "capitalize", margin: 0 }}>{monthName}</h3>
                        <div style={{ display: "flex", gap: 4 }}>
                          <button style={{ width: 32, height: 32, borderRadius: 6, border: "1px solid var(--rule)", background: "transparent", cursor: "pointer", color: "var(--muted)" }}>‹</button>
                          <button style={{ width: 32, height: 32, borderRadius: 6, border: "1px solid var(--rule)", background: "transparent", cursor: "pointer" }}>›</button>
                        </div>
                      </div>
                      <div style={{ display: "grid", gridTemplateColumns: "repeat(7, 1fr)", gap: 4, marginBottom: 8 }}>
                        {["L", "M", "M", "J", "V", "S", "D"].map((d, i) => (
                          <div key={i} className="caption" style={{ textAlign: "center", fontSize: 10, padding: "6px 0" }}>{d}</div>
                        ))}
                      </div>
                      <div style={{ display: "grid", gridTemplateColumns: "repeat(7, 1fr)", gap: 4 }}>
                        {cells.map((c, i) => {
                          if (!c) return <div key={i} />;
                          const isSelected = selectedDate && selectedDate.d === c.d;
                          return (
                            <button
                              key={i}
                              onClick={() => pick(c)}
                              disabled={!c.available}
                              style={{
                                aspectRatio: "1",
                                borderRadius: 8,
                                border: isSelected ? "1.5px solid var(--ink)" : "1px solid transparent",
                                background: isSelected ? "var(--ink)" : c.available ? "var(--accent-wash)" : "transparent",
                                color: isSelected ? "var(--bg)" : c.available ? "var(--ink)" : "var(--muted)",
                                fontSize: 13,
                                fontWeight: isSelected ? 600 : 500,
                                cursor: c.available ? "pointer" : "not-allowed",
                                fontFamily: "var(--sans)",
                                transition: "all 0.12s ease",
                                opacity: c.available ? 1 : 0.35,
                              }}
                            >{c.d}</button>
                          );
                        })}
                      </div>
                      <div style={{ marginTop: 20, display: "flex", gap: 16, fontSize: 11, color: "var(--muted)" }}>
                        <span style={{ display: "flex", alignItems: "center", gap: 6 }}>
                          <span style={{ width: 8, height: 8, borderRadius: 2, background: "var(--accent-wash)" }}/> Disponible
                        </span>
                        <span style={{ display: "flex", alignItems: "center", gap: 6 }}>
                          <span style={{ width: 8, height: 8, borderRadius: 2, background: "var(--ink)" }}/> Seleccionado
                        </span>
                      </div>
                    </div>

                    {/* Times */}
                    <div style={{ borderLeft: "1px solid var(--rule)", paddingLeft: 28 }}>
                      <div className="caption" style={{ marginBottom: 14 }}>
                        {selectedDate ? fmt(selectedDate.dt) : "Selecciona un día"}
                      </div>
                      {selectedDate ? (
                        <div style={{ display: "flex", flexDirection: "column", gap: 6, maxHeight: 340, overflow: "auto" }}>
                          {times.map(t => (
                            <button
                              key={t}
                              onClick={() => setSelectedTime(t)}
                              style={{
                                padding: "12px 16px",
                                border: selectedTime === t ? "1.5px solid var(--ink)" : "1px solid var(--rule)",
                                background: selectedTime === t ? "var(--ink)" : "var(--paper)",
                                color: selectedTime === t ? "var(--bg)" : "var(--ink)",
                                borderRadius: 8,
                                fontSize: 13,
                                fontFamily: "var(--mono)",
                                fontWeight: 500,
                                cursor: "pointer",
                                textAlign: "center",
                                transition: "all 0.1s",
                              }}
                            >{t}</button>
                          ))}
                        </div>
                      ) : (
                        <div style={{ fontSize: 12, color: "var(--muted)", fontStyle: "italic", paddingTop: 8 }}>
                          Elige un día disponible para ver los horarios.
                        </div>
                      )}
                      {selectedDate && selectedTime && (
                        <button
                          onClick={confirm}
                          className="btn btn-primary"
                          style={{ width: "100%", marginTop: 20, justifyContent: "center", padding: "13px 22px" }}
                        >
                          Continuar
                          <svg width="12" height="12" viewBox="0 0 24 24" fill="none"><path d="M5 12h14M13 6l6 6-6 6" stroke="currentColor" strokeWidth="2"/></svg>
                        </button>
                      )}
                    </div>
                  </div>
                </div>
              )}

              {step === 1 && (
                <div style={{ padding: 36, background: "var(--paper)" }}>
                  <button onClick={() => setStep(0)} className="btn-link" style={{ fontSize: 13, marginBottom: 20, display: "flex", alignItems: "center", gap: 6 }}>
                    <span className="arrow" style={{ transform: "rotate(180deg)", display: "inline-block" }}>→</span> Cambiar horario
                  </button>
                  <div style={{ padding: "14px 18px", background: "var(--accent-wash)", borderRadius: 8, marginBottom: 28, display: "flex", alignItems: "center", gap: 12 }}>
                    <svg width="18" height="18" viewBox="0 0 24 24" fill="none"><rect x="3" y="5" width="18" height="16" rx="2" stroke="currentColor" strokeWidth="1.8"/><path d="M3 9h18M8 3v4M16 3v4" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round"/></svg>
                    <div>
                      <div style={{ fontSize: 13, fontWeight: 500, textTransform: "capitalize" }}>{fmt(selectedDate.dt)} · {selectedTime}</div>
                      <div style={{ fontSize: 11, color: "var(--ink-2)", marginTop: 2 }}>45 minutos · Google Meet</div>
                    </div>
                  </div>

                  <h3 className="serif" style={{ fontSize: 22, marginBottom: 6 }}>Cuéntanos sobre ti</h3>
                  <p style={{ fontSize: 13, color: "var(--muted)", margin: "0 0 24px" }}>Así llegamos preparados a la llamada.</p>

                  <form onSubmit={submit} style={{ display: "flex", flexDirection: "column", gap: 16 }}>
                    <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12 }}>
                      <Field label="Nombre" value={form.name} onChange={v => setForm(f => ({...f, name: v}))} required />
                      <Field label="Email de trabajo" type="email" value={form.email} onChange={v => setForm(f => ({...f, email: v}))} required />
                    </div>
                    <Field label="Empresa" value={form.company} onChange={v => setForm(f => ({...f, company: v}))} required />
                    <div>
                      <label style={{ fontSize: 11, color: "var(--muted)", textTransform: "uppercase", letterSpacing: "0.08em", fontFamily: "var(--mono)", marginBottom: 8, display: "block" }}>Documentos por mes (aproximado)</label>
                      <div style={{ display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: 8 }}>
                        {["< 500", "500 – 2k", "2k – 5k", "5k+"].map(opt => (
                          <button
                            type="button"
                            key={opt}
                            onClick={() => setForm(f => ({...f, docs: opt}))}
                            style={{
                              padding: "10px 8px",
                              border: form.docs === opt ? "1.5px solid var(--ink)" : "1px solid var(--rule)",
                              background: form.docs === opt ? "var(--ink)" : "var(--paper)",
                              color: form.docs === opt ? "var(--bg)" : "var(--ink)",
                              borderRadius: 6,
                              fontSize: 12,
                              cursor: "pointer",
                              fontFamily: "var(--sans)",
                            }}
                          >{opt}</button>
                        ))}
                      </div>
                    </div>
                    <div>
                      <label style={{ fontSize: 11, color: "var(--muted)", textTransform: "uppercase", letterSpacing: "0.08em", fontFamily: "var(--mono)", marginBottom: 8, display: "block" }}>¿Algo que te gustaría que preparemos? <span style={{ textTransform: "none", fontStyle: "italic", color: "var(--muted)", fontFamily: "var(--serif)", letterSpacing: 0 }}>(opcional)</span></label>
                      <textarea
                        value={form.msg}
                        onChange={e => setForm(f => ({...f, msg: e.target.value}))}
                        rows={3}
                        style={{ width: "100%", padding: "12px 14px", border: "1px solid var(--rule)", borderRadius: 8, fontSize: 14, fontFamily: "var(--sans)", resize: "vertical", background: "var(--paper)", color: "var(--ink)" }}
                        placeholder="Cuéntanos sobre tu operación, integraciones que usas, dudas específicas..."
                      />
                    </div>
                    <button type="submit" className="btn btn-primary" style={{ marginTop: 8, justifyContent: "center", padding: "14px 22px" }}>
                      Confirmar reunión
                      <svg width="14" height="14" viewBox="0 0 24 24" fill="none"><path d="M5 12l5 5L20 7" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round"/></svg>
                    </button>
                  </form>
                </div>
              )}

              {step === 2 && (
                <div style={{ padding: "72px 48px", background: "var(--paper)", textAlign: "center", position: "relative" }}>
                  <div style={{ position: "absolute", top: 24, right: 28, opacity: 0.9 }}>
                    <Mascot pose="celebrate" size={80} />
                  </div>
                  <div style={{ width: 64, height: 64, borderRadius: "50%", background: "oklch(0.55 0.18 135)", display: "grid", placeItems: "center", margin: "0 auto 28px" }}>
                    <svg width="32" height="32" viewBox="0 0 24 24" fill="none"><path d="M5 12l5 5L20 7" stroke="#0a0a0a" strokeWidth="3" strokeLinecap="round" strokeLinejoin="round"/></svg>
                  </div>
                  <h3 className="display-3 serif" style={{ marginBottom: 14 }}>¡Listo, {form.name.split(" ")[0] || "nos vemos"}!</h3>
                  <p style={{ color: "var(--ink-2)", fontSize: 16, maxWidth: "40ch", margin: "0 auto 32px", lineHeight: 1.5 }}>
                    Te enviamos una invitación a <strong>{form.email}</strong> con el link de Google Meet.
                  </p>
                  <div style={{ padding: 20, background: "var(--bg-2)", borderRadius: 10, display: "inline-flex", gap: 20, fontSize: 13, alignItems: "center" }}>
                    <div style={{ textTransform: "capitalize" }}>
                      <div className="caption" style={{ fontSize: 10, marginBottom: 4 }}>Cuándo</div>
                      <div style={{ fontWeight: 500 }}>{fmt(selectedDate.dt)}</div>
                    </div>
                    <div style={{ width: 1, height: 28, background: "var(--rule)" }}/>
                    <div>
                      <div className="caption" style={{ fontSize: 10, marginBottom: 4 }}>Hora</div>
                      <div style={{ fontWeight: 500, fontFamily: "var(--mono)" }}>{selectedTime}</div>
                    </div>
                  </div>
                  <div style={{ marginTop: 40, display: "flex", gap: 10, justifyContent: "center" }}>
                    <a className="btn btn-ghost" href="index.html">Volver al inicio</a>
                    <a className="btn btn-primary" href="producto.html">Explorar producto</a>
                  </div>
                </div>
              )}
                </>
              )}

            </div>
          </div>
        </div>
      </section>

      {/* Trust strip */}
      <section style={{ padding: "56px 0", background: "var(--bg-2)", borderTop: "1px solid var(--rule)" }}>
        <div className="container-wide">
          <div style={{ display: "grid", gridTemplateColumns: "1fr 2fr", gap: 64, alignItems: "center" }}>
            <div>
              <div className="eyebrow"><span className="dot"/>Confianza</div>
              <h2 className="serif" style={{ fontSize: 28, marginTop: 12, letterSpacing: "-0.01em" }}>
                500+ empresas chilenas ya operan con Wasabil.
              </h2>
            </div>
            <div style={{ display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: 24 }}>
              {[
                { n: "500+", l: "Empresas" },
                { n: "$2.4B", l: "Facturado / año" },
                { n: "10 min", l: "Onboarding" },
                { n: "99%", l: "Precisión SII" },
              ].map((s, i) => (
                <div key={i}>
                  <div className="serif" style={{ fontSize: 36, lineHeight: 1 }}>{s.n}</div>
                  <div className="caption" style={{ marginTop: 8 }}>{s.l}</div>
                </div>
              ))}
            </div>
          </div>
        </div>
      </section>

      <Footer />
    </>
  );
}

function Field({ label, type = "text", value, onChange, required }) {
  return (
    <div>
      <label style={{ fontSize: 11, color: "var(--muted)", textTransform: "uppercase", letterSpacing: "0.08em", fontFamily: "var(--mono)", marginBottom: 8, display: "block" }}>
        {label} {required && <span style={{ color: "var(--muted)" }}>*</span>}
      </label>
      <input
        type={type}
        value={value}
        onChange={e => onChange(e.target.value)}
        required={required}
        style={{ width: "100%", padding: "12px 14px", border: "1px solid var(--rule)", borderRadius: 8, fontSize: 14, fontFamily: "var(--sans)", background: "var(--paper)", color: "var(--ink)" }}
      />
    </div>
  );
}
