/* =====================================================================
   result.jsx — Pantalla de resultado + modales (Calendly, Stripe, email,
   compartir, contacto). Todos los "backends" están simulados de forma
   creíble y marcados con // MOCK para el handoff al dev.
   ===================================================================== */
const RC = window.Cotizador;

/* --- Modal de contacto (escalas grandes que abren "Contactar equipo") --- */
function ContactModal({ open, onClose }) {
  const [sent, setSent] = useStateUI(false);
  useEffectUI(() => { if (open) setSent(false); }, [open]);
  return (
    <Modal open={open} onClose={onClose} maxWidth={460} labelledBy="contact-title">
      <div style={{ padding: 28 }}>
        {!sent ? (
          <React.Fragment>
            <span style={{ width: 44, height: 44, borderRadius: "var(--radius-md)", background: "var(--accent-500)", color: "var(--navy-900)", display: "flex", alignItems: "center", justifyContent: "center", marginBottom: 16 }}>
              <Icon name="users" size={22} />
            </span>
            <h3 id="contact-title" style={{ fontFamily: "var(--font-display)", fontSize: 22, fontWeight: 600, color: "var(--navy-900)", letterSpacing: "-0.01em", margin: 0 }}>Hablemos de tu proyecto a medida</h3>
            <p style={{ marginTop: 10, fontSize: 14.5, lineHeight: "22px", color: "var(--fg-secondary)" }}>Para este tamaño preferimos cotizar contigo en una llamada. Déjanos tu correo y un especialista te contacta en menos de 24 horas.</p>
            <input type="email" placeholder="tu@correo.com" className="cotz-input" style={{ width: "100%", marginTop: 18 }} />
            <button type="button" className="cotz-btn cotz-btn-primary" style={{ width: "100%", marginTop: 12, justifyContent: "center" }} onClick={() => setSent(true)}>Contactar al equipo</button>
            <button type="button" className="cotz-btn cotz-btn-ghost" style={{ width: "100%", marginTop: 8, justifyContent: "center" }} onClick={onClose}>Volver a las opciones</button>
          </React.Fragment>
        ) : (
          <div style={{ textAlign: "center", padding: "12px 0" }}>
            <span style={{ width: 52, height: 52, borderRadius: 999, background: "var(--success-100)", color: "var(--success-700)", display: "inline-flex", alignItems: "center", justifyContent: "center", marginBottom: 14 }}>
              <Icon name="check" size={26} strokeWidth={2.5} />
            </span>
            <h3 style={{ fontFamily: "var(--font-display)", fontSize: 20, fontWeight: 600, color: "var(--navy-900)", margin: 0 }}>Recibido</h3>
            <p style={{ marginTop: 8, fontSize: 14.5, color: "var(--fg-secondary)" }}>Te escribiremos por correo muy pronto.</p>
            <button type="button" className="cotz-btn cotz-btn-secondary" style={{ marginTop: 18, justifyContent: "center" }} onClick={onClose}>Cerrar</button>
          </div>
        )}
      </div>
    </Modal>
  );
}

/* --- Modal Calendly (mock) --- */
function CalendlyModal({ open, onClose }) {
  const [day, setDay] = useStateUI(null);
  const [slot, setSlot] = useStateUI(null);
  const [done, setDone] = useStateUI(false);
  useEffectUI(() => { if (open) { setDay(null); setSlot(null); setDone(false); } }, [open]);

  const days = [];
  const base = new Date();
  const dow = ["dom", "lun", "mar", "mié", "jue", "vie", "sáb"];
  const mon = ["ene", "feb", "mar", "abr", "may", "jun", "jul", "ago", "sep", "oct", "nov", "dic"];
  let added = 0, cursor = 1;
  while (added < 8) {
    const d = new Date(base.getTime() + cursor * 86400000);
    if (d.getDay() !== 0 && d.getDay() !== 6) { days.push(d); added++; }
    cursor++;
  }
  const slots = ["9:00", "10:30", "12:00", "14:00", "15:30", "17:00"];

  return (
    <Modal open={open} onClose={onClose} maxWidth={560} labelledBy="cal-title">
      <div style={{ display: "flex", alignItems: "center", gap: 12, padding: "18px 24px", borderBottom: "1px solid var(--border-default)" }}>
        <span style={{ width: 36, height: 36, borderRadius: "var(--radius-md)", background: "var(--navy-700)", color: "var(--paper)", display: "flex", alignItems: "center", justifyContent: "center" }}>
          <Icon name="calendar-clock" size={18} />
        </span>
        <div style={{ flex: 1 }}>
          <h3 id="cal-title" style={{ fontFamily: "var(--font-display)", fontSize: 17, fontWeight: 600, color: "var(--navy-900)", margin: 0 }}>Agenda una llamada · 30 min</h3>
          <div style={{ fontSize: 12.5, color: "var(--fg-tertiary)" }}>Con un especialista de Sell-U · zona horaria local</div>
        </div>
        <button type="button" aria-label="Cerrar" className="cotz-iconbtn" onClick={onClose}><Icon name="x" size={18} /></button>
      </div>

      {!done ? (
        <div style={{ padding: 24 }}>
          <div style={{ fontSize: 12, fontWeight: 600, letterSpacing: "0.12em", textTransform: "uppercase", color: "var(--fg-tertiary)", marginBottom: 12 }}>Elige un día</div>
          <div style={{ display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: 8 }}>
            {days.map((d, i) => {
              const sel = day === i;
              return (
                <button key={i} type="button" onClick={() => { setDay(i); setSlot(null); }} style={{
                  cursor: "pointer", borderRadius: "var(--radius-md)", padding: "10px 4px", textAlign: "center",
                  border: "1.5px solid " + (sel ? "var(--navy-700)" : "var(--border-default)"),
                  background: sel ? "var(--navy-700)" : "var(--white)", color: sel ? "var(--paper)" : "var(--navy-900)",
                  transition: "all 160ms var(--ease-out)",
                }}>
                  <div style={{ fontSize: 11, textTransform: "uppercase", letterSpacing: "0.06em", opacity: 0.7 }}>{dow[d.getDay()]}</div>
                  <div style={{ fontFamily: "var(--font-display)", fontSize: 18, fontWeight: 600 }}>{d.getDate()}</div>
                  <div style={{ fontSize: 11, opacity: 0.7 }}>{mon[d.getMonth()]}</div>
                </button>
              );
            })}
          </div>
          {day !== null && (
            <div style={{ marginTop: 22, animation: "cotz-step 200ms var(--ease-out)" }}>
              <div style={{ fontSize: 12, fontWeight: 600, letterSpacing: "0.12em", textTransform: "uppercase", color: "var(--fg-tertiary)", marginBottom: 12 }}>Elige un horario</div>
              <div style={{ display: "grid", gridTemplateColumns: "repeat(3, 1fr)", gap: 8 }}>
                {slots.map(s => {
                  const sel = slot === s;
                  return (
                    <button key={s} type="button" onClick={() => setSlot(s)} style={{
                      cursor: "pointer", borderRadius: "var(--radius-md)", padding: "11px 4px", fontWeight: 600, fontSize: 14,
                      border: "1.5px solid " + (sel ? "var(--navy-700)" : "var(--border-strong)"),
                      background: sel ? "var(--navy-700)" : "var(--white)", color: sel ? "var(--paper)" : "var(--navy-900)",
                      transition: "all 160ms var(--ease-out)",
                    }}>{s}</button>
                  );
                })}
              </div>
            </div>
          )}
          <button type="button" className="cotz-btn cotz-btn-primary" disabled={slot === null} style={{ width: "100%", justifyContent: "center", marginTop: 24, opacity: slot === null ? 0.5 : 1, cursor: slot === null ? "not-allowed" : "pointer" }} onClick={() => setDone(true)}>
            Confirmar llamada
          </button>
          <div style={{ marginTop: 10, fontSize: 11.5, color: "var(--fg-muted)", textAlign: "center" }}>{/* MOCK: aquí se incrustaría el iframe real de Calendly */}Demo · integración Calendly simulada</div>
        </div>
      ) : (
        <div style={{ padding: "36px 24px", textAlign: "center" }}>
          <span style={{ width: 56, height: 56, borderRadius: 999, background: "var(--success-100)", color: "var(--success-700)", display: "inline-flex", alignItems: "center", justifyContent: "center", marginBottom: 16 }}>
            <Icon name="calendar-check" size={26} strokeWidth={2} />
          </span>
          <h3 style={{ fontFamily: "var(--font-display)", fontSize: 21, fontWeight: 600, color: "var(--navy-900)", margin: 0 }}>Llamada agendada</h3>
          <p style={{ marginTop: 10, fontSize: 14.5, color: "var(--fg-secondary)" }}>
            {dow[days[day].getDay()]} {days[day].getDate()} de {mon[days[day].getMonth()]} · {slot} h.<br />Te enviamos la invitación por correo.
          </p>
          <button type="button" className="cotz-btn cotz-btn-secondary" style={{ marginTop: 20, justifyContent: "center" }} onClick={onClose}>Listo</button>
        </div>
      )}
    </Modal>
  );
}

/* --- Modal Stripe (mock checkout) --- */
function StripeModal({ open, onClose, deposit }) {
  const [done, setDone] = useStateUI(false);
  useEffectUI(() => { if (open) setDone(false); }, [open]);
  return (
    <Modal open={open} onClose={onClose} maxWidth={460} labelledBy="stripe-title">
      <div style={{ display: "flex", alignItems: "center", gap: 12, padding: "18px 24px", borderBottom: "1px solid var(--border-default)" }}>
        <span style={{ width: 36, height: 36, borderRadius: "var(--radius-md)", background: "var(--navy-700)", color: "var(--paper)", display: "flex", alignItems: "center", justifyContent: "center" }}>
          <Icon name="lock" size={16} />
        </span>
        <h3 id="stripe-title" style={{ flex: 1, fontFamily: "var(--font-display)", fontSize: 17, fontWeight: 600, color: "var(--navy-900)", margin: 0 }}>Bloquear tu cupo</h3>
        <button type="button" aria-label="Cerrar" className="cotz-iconbtn" onClick={onClose}><Icon name="x" size={18} /></button>
      </div>
      {!done ? (
        <div style={{ padding: 24 }}>
          <div style={{ background: "var(--paper-2)", borderRadius: "var(--radius-md)", padding: "16px 18px", display: "flex", justifyContent: "space-between", alignItems: "center" }}>
            <div>
              <div style={{ fontSize: 13, color: "var(--fg-tertiary)" }}>Anticipo (50%)</div>
              <div style={{ fontSize: 12, color: "var(--fg-muted)", marginTop: 2 }}>Se descuenta del total final</div>
            </div>
            <div style={{ fontFamily: "var(--font-display)", fontSize: 26, fontWeight: 600, color: "var(--navy-900)", letterSpacing: "-0.01em" }}>{RC.fmtUSD(deposit)} <span style={{ fontSize: 13, color: "var(--fg-tertiary)", fontWeight: 400 }}>USD</span></div>
          </div>
          <div style={{ marginTop: 18, display: "flex", flexDirection: "column", gap: 12 }}>
            <input className="cotz-input" placeholder="Correo" defaultValue="" />
            <input className="cotz-input" placeholder="Número de tarjeta" defaultValue="4242 4242 4242 4242" style={{ fontFamily: "var(--font-mono)" }} />
            <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12 }}>
              <input className="cotz-input" placeholder="MM / AA" defaultValue="12 / 28" style={{ fontFamily: "var(--font-mono)" }} />
              <input className="cotz-input" placeholder="CVC" defaultValue="123" style={{ fontFamily: "var(--font-mono)" }} />
            </div>
          </div>
          <button type="button" className="cotz-btn cotz-btn-primary" style={{ width: "100%", justifyContent: "center", marginTop: 18 }} onClick={() => setDone(true)}>
            Pagar {RC.fmtUSD(deposit)} y reservar
          </button>
          <div style={{ marginTop: 12, fontSize: 11.5, color: "var(--fg-muted)", textAlign: "center", display: "flex", gap: 6, justifyContent: "center", alignItems: "center" }}>
            <Icon name="shield-check" size={13} /> {/* MOCK: redirección real a Stripe Checkout */}Pago seguro · demo simulada
          </div>
        </div>
      ) : (
        <div style={{ padding: "36px 24px", textAlign: "center" }}>
          <span style={{ width: 56, height: 56, borderRadius: 999, background: "var(--success-100)", color: "var(--success-700)", display: "inline-flex", alignItems: "center", justifyContent: "center", marginBottom: 16 }}>
            <Icon name="check" size={28} strokeWidth={2.5} />
          </span>
          <h3 style={{ fontFamily: "var(--font-display)", fontSize: 21, fontWeight: 600, color: "var(--navy-900)", margin: 0 }}>Cupo reservado</h3>
          <p style={{ marginTop: 10, fontSize: 14.5, color: "var(--fg-secondary)" }}>Recibimos tu anticipo de {RC.fmtUSD(deposit)} USD. Arrancamos tu proyecto y te escribimos por correo.</p>
          <button type="button" className="cotz-btn cotz-btn-secondary" style={{ marginTop: 20, justifyContent: "center" }} onClick={onClose}>Cerrar</button>
        </div>
      )}
    </Modal>
  );
}

/* --- Modal de email --- */
function EmailModal({ open, onClose }) {
  const [sent, setSent] = useStateUI(false);
  const [email, setEmail] = useStateUI("");
  useEffectUI(() => { if (open) { setSent(false); setEmail(""); } }, [open]);
  const valid = /.+@.+\..+/.test(email);
  return (
    <Modal open={open} onClose={onClose} maxWidth={420} labelledBy="email-title">
      <div style={{ padding: 28 }}>
        {!sent ? (
          <React.Fragment>
            <span style={{ width: 44, height: 44, borderRadius: "var(--radius-md)", background: "var(--paper-2)", color: "var(--navy-700)", display: "flex", alignItems: "center", justifyContent: "center", marginBottom: 16 }}>
              <Icon name="mail" size={22} />
            </span>
            <h3 id="email-title" style={{ fontFamily: "var(--font-display)", fontSize: 20, fontWeight: 600, color: "var(--navy-900)", margin: 0 }}>Enviarte esta cotización</h3>
            <p style={{ marginTop: 8, fontSize: 14, lineHeight: "21px", color: "var(--fg-secondary)" }}>Te mandamos el desglose completo y el enlace para reabrirla cuando quieras.</p>
            <input type="email" value={email} onChange={(e) => setEmail(e.target.value)} placeholder="tu@correo.com" className="cotz-input" style={{ width: "100%", marginTop: 16 }} />
            <button type="button" className="cotz-btn cotz-btn-primary" disabled={!valid} style={{ width: "100%", justifyContent: "center", marginTop: 12, opacity: valid ? 1 : 0.5, cursor: valid ? "pointer" : "not-allowed" }} onClick={() => setSent(true)}>Enviar cotización</button>
          </React.Fragment>
        ) : (
          <div style={{ textAlign: "center", padding: "8px 0" }}>
            <span style={{ width: 52, height: 52, borderRadius: 999, background: "var(--success-100)", color: "var(--success-700)", display: "inline-flex", alignItems: "center", justifyContent: "center", marginBottom: 14 }}>
              <Icon name="send" size={22} />
            </span>
            <h3 style={{ fontFamily: "var(--font-display)", fontSize: 19, fontWeight: 600, color: "var(--navy-900)", margin: 0 }}>Enviada</h3>
            <p style={{ marginTop: 8, fontSize: 14, color: "var(--fg-secondary)" }}>Revisa <strong style={{ color: "var(--navy-900)" }}>{email}</strong> en unos minutos.</p>
            <button type="button" className="cotz-btn cotz-btn-secondary" style={{ marginTop: 18, justifyContent: "center" }} onClick={onClose}>Cerrar</button>
          </div>
        )}
      </div>
    </Modal>
  );
}

Object.assign(window, { ContactModal, CalendlyModal, StripeModal, EmailModal });
