/* RegistroModal.jsx — Captura nombre + correo con validacion en dos capas:
 *   1. Lista negra de dominios desechables
 *   2. Abstract API (si esta configurada)
 * Tras registro exitoso muestra ThanksScreen con animacion corporativa.
 * Exposed as window.RegistroModal.
 */
function RegistroModal({ open, doc, onClose, onSuccess }) {
  const [name, setName] = React.useState("");
  const [email, setEmail] = React.useState("");
  const [error, setError] = React.useState("");
  const [sending, setSending] = React.useState(false);
  const [validating, setValidating] = React.useState(false);
  const [thanks, setThanks] = React.useState(false);
  const [pendingDoc, setPendingDoc] = React.useState(null);

  React.useEffect(() => {
    if (open) { setName(""); setEmail(""); setError(""); setSending(false); setValidating(false); setThanks(false); setPendingDoc(null); }
  }, [open, doc]);

  React.useEffect(() => {
    const onKey = (e) => { if (e.key === "Escape" && !thanks) onClose(); };
    if (open) window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, [open, onClose, thanks]);

  React.useEffect(() => {
    if (thanks && window.lucide) setTimeout(() => window.lucide.createIcons(), 60);
  }, [thanks]);

  if (!open) return null;

  const handleSubmit = async (e) => {
    e.preventDefault();
    if (!name.trim()) { setError("Ingrese su nombre completo"); return; }

    setSending(true);
    setValidating(true);
    setError("");

    // Validar correo (formato + lista negra + Abstract API si esta configurada)
    const result = await EmailValidator.validate(email);
    setValidating(false);

    if (!result.valid) {
      setError(result.reason || "Correo no valido");
      setSending(false);
      return;
    }

    // Guardar lead en Supabase
    await LeadStore.addLead({
      name: name.trim(),
      email: email.trim(),
      docId: doc ? doc.id : "",
      docName: doc ? doc.name : "",
    });

    // Marcar registro unico en este navegador
    LeadStore.markRegistered(name.trim(), email.trim());

    // Guardar el doc pendiente y mostrar pantalla de gracias
    setPendingDoc(doc);
    setSending(false);
    setThanks(true);
  };

  const handleContinue = () => {
    setThanks(false);
    onSuccess(pendingDoc);
  };

  // Si estamos en la pantalla de gracias, renderizarla en lugar del modal
  if (thanks) {
    return (
      <ThanksScreen
        open={true}
        name={name}
        onContinue={handleContinue}
      />
    );
  }

  return (
    <div className="reg-modal-overlay" onClick={onClose}>
      <div className="reg-modal" onClick={e => e.stopPropagation()} role="dialog" aria-modal="true" aria-labelledby="reg-modal-title">
        <button className="reg-modal-close" onClick={onClose} aria-label="Cerrar">
          <i data-lucide="x"></i>
        </button>
        <div className="reg-modal-icon">
          <i data-lucide="shield-check"></i>
        </div>
        <h2 id="reg-modal-title" className="reg-modal-title">Acceso con registro</h2>
        <p className="reg-modal-lede">
          Para acceder a <strong>{doc && doc.name}</strong> ingresa tus datos.
          Es rapido, gratuito y solo se hace una vez.
        </p>
        <form onSubmit={handleSubmit} className="reg-modal-form">
          <div className="reg-field">
            <label>Nombre completo</label>
            <input
              type="text"
              value={name}
              onChange={e => setName(e.target.value)}
              placeholder="Su nombre"
              autoFocus
              disabled={sending}
            />
          </div>
          <div className={"reg-field" + (validating ? " reg-field-validating" : "")}>
            <label>
              Correo electronico
              {EmailValidator.hasApiKey() && (
                <span style={{ fontWeight: 400, fontSize: 11, color: "var(--hl-fg-3)", marginLeft: 8 }}>
                  verificado
                </span>
              )}
            </label>
            <input
              type="email"
              value={email}
              onChange={e => setEmail(e.target.value)}
              placeholder="correo@ejemplo.com"
              disabled={sending}
              style={{ paddingRight: validating ? 42 : undefined }}
            />
          </div>
          {error && (
            <div className="reg-modal-error" style={{ display: "flex", alignItems: "center", gap: 8 }}>
              <i data-lucide="alert-circle" style={{ width: 15, height: 15, flexShrink: 0 }}></i>
              {error}
            </div>
          )}
          <button type="submit" className="reg-modal-submit" disabled={sending}>
            {validating ? "Verificando correo…" : sending ? "Enviando…" : "Acceder al documento"}
          </button>
          <p className="reg-modal-note">
            Registro unico — despues podras descargar todos los recursos sin volver a ingresar tus datos.
          </p>
        </form>
      </div>
    </div>
  );
}

Object.assign(window, { RegistroModal });
