// Sign Up screen — single-page form, profesores-first
const { useState } = React;

function SignUp() {
  const [pwd, setPwd] = useState("");
  const [showPwd, setShowPwd] = useState(false);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState("");
  const strength = pwd.length === 0 ? 0 : pwd.length < 6 ? 1 : pwd.length < 10 ? 2 : 3;

  async function handleSubmit(e) {
    e.preventDefault();
    setError("");

    const nombre   = document.getElementById('su-name').value.trim();
    const apellido = document.getElementById('su-last').value.trim();
    const email    = document.getElementById('su-email').value.trim();
    const colegio  = document.getElementById('su-school').value.trim();
    const asignatura = document.getElementById('su-subject').value;
    const nivel    = document.getElementById('su-grade').value;

    if (pwd.length < 8) {
      return setError("La contraseña debe tener al menos 8 caracteres.");
    }

    setLoading(true);

    const { error: authError } = await authClient.auth.signUp({
      email,
      password: pwd,
      options: {
        emailRedirectTo: 'https://alquie.com/Email Confirmed.html',
        data: { nombre, apellido, colegio, asignatura, nivel, rol: 'profesor' }
      }
    });

    setLoading(false);

    if (authError) {
      const msgs = {
        'User already registered': 'Ya existe una cuenta con ese correo. ¿Quieres iniciar sesión?',
        'Password should be at least 6 characters': 'La contraseña es muy corta.',
      };
      return setError(msgs[authError.message] || authError.message);
    }

    sessionStorage.setItem('alquie_reg_email', email);
    sessionStorage.setItem('alquie_reg_nombre', nombre);
    window.location.href = "Email Check.html";
  }

  async function handleGoogle() {
    await authClient.auth.signInWithOAuth({
      provider: 'google',
      options: { redirectTo: window.location.origin + '/Email Confirmed.html' }
    });
  }

  return (
    <div className="auth-shell">
      <div className="auth-form-pane">
        <AuthTopbar />

        <div className="auth-form-wrap">
          <span className="auth-eyebrow">Para profesores</span>
          <h1 className="auth-h1">
            Crea tu cuenta y empieza <span className="accent">gratis</span>.
          </h1>
          <p className="auth-lead">
            Sin tarjeta. Activas tu primera clase en menos de 5 minutos.
          </p>

          <form className="auth-form" onSubmit={handleSubmit}>
            <button type="button" className="auth-btn auth-btn--google" onClick={handleGoogle}>
              <GoogleIcon />
              Continuar con Google
            </button>

            <div className="auth-divider">o con tu correo</div>

            <div className="auth-row auth-row--2">
              <div className="auth-field">
                <label htmlFor="su-name">Nombre</label>
                <input id="su-name" type="text" placeholder="Carolina" required />
              </div>
              <div className="auth-field">
                <label htmlFor="su-last">Apellido</label>
                <input id="su-last" type="text" placeholder="Méndez" required />
              </div>
            </div>

            <div className="auth-field auth-field--with-icon">
              <label htmlFor="su-email">Correo</label>
              <span className="auth-field__icon"><MailIcon /></span>
              <input id="su-email" type="email" placeholder="carolina@miscolegios.cl" required />
            </div>

            <div className="auth-field">
              <label htmlFor="su-pwd">Contraseña</label>
              <div className="auth-input-wrap">
                <input
                  id="su-pwd"
                  type={showPwd ? "text" : "password"}
                  placeholder="Mínimo 8 caracteres"
                  value={pwd}
                  onChange={(e) => setPwd(e.target.value)}
                  style={{ paddingRight: 46 }}
                  required
                />
                <button
                  type="button"
                  className="auth-field__toggle"
                  onClick={() => setShowPwd((v) => !v)}
                  aria-label={showPwd ? "Ocultar contraseña" : "Mostrar contraseña"}
                >
                  {showPwd ? (
                    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M17.94 17.94A10.94 10.94 0 0 1 12 20c-7 0-11-8-11-8a19.5 19.5 0 0 1 5.06-5.94"/><path d="M9.9 4.24A10.94 10.94 0 0 1 12 4c7 0 11 8 11 8a19.5 19.5 0 0 1-2.16 3.19"/><path d="M14.12 14.12a3 3 0 1 1-4.24-4.24"/><line x1="1" y1="1" x2="23" y2="23"/></svg>
                  ) : (
                    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"/><circle cx="12" cy="12" r="3"/></svg>
                  )}
                </button>
              </div>
              <div className="auth-strength">
                <div className={"auth-strength__bar" + (strength >= 1 ? " is-on-1" : "")} />
                <div className={"auth-strength__bar" + (strength >= 2 ? " is-on-2" : "")} />
                <div className={"auth-strength__bar" + (strength >= 3 ? " is-on-3" : "")} />
              </div>
            </div>

            <div className="auth-field">
              <label htmlFor="su-school">Colegio donde enseñas</label>
              <input id="su-school" type="text" placeholder="Colegio San Ignacio" />
            </div>

            <div className="auth-row auth-row--2">
              <div className="auth-field">
                <label htmlFor="su-subject">Asignatura principal</label>
                <select id="su-subject" defaultValue="">
                  <option value="" disabled>Selecciona…</option>
                  <option>Matemáticas</option>
                  <option>Lenguaje</option>
                  <option>Ciencias</option>
                  <option>Historia</option>
                  <option>Inglés</option>
                  <option>Otra</option>
                </select>
              </div>
              <div className="auth-field">
                <label htmlFor="su-grade">Nivel / curso</label>
                <select id="su-grade" defaultValue="">
                  <option value="" disabled>Selecciona…</option>
                  <option>1° a 4° básico</option>
                  <option>5° a 8° básico</option>
                  <option>1° a 2° medio</option>
                  <option>3° a 4° medio</option>
                  <option>Mixto</option>
                </select>
              </div>
            </div>

            {error && <p style={{ color: '#e05252', fontSize: 13, margin: '-4px 0 4px' }}>{error}</p>}

            <button type="submit" className="auth-btn auth-btn--primary" style={{ marginTop: 10 }} disabled={loading}>
              {loading ? "Creando tu cuenta…" : "Crear mi cuenta gratis"}
            </button>

            <p className="auth-terms">
              Al crear tu cuenta aceptas los <a href="#terms">Términos</a> y la <a href="#privacy">Política de privacidad</a>.
            </p>
          </form>
        </div>

        <AuthFooter />
      </div>

      <AuthVisual />
    </div>
  );
}

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