/* ============================================================
   Login / Registration
   - step "email"    → enter email (routes to the right next step)
   - step "password" → returning user enters their password
   - step "setpw"    → legacy/admin-created account creates a password
   - step "details"  → first-time user: name + área + password
   ============================================================ */

function RegisterScreen({ prefillEmail, onDone }) {
  const Q = window.QStore;
  const [step, setStep] = useState("email");
  const [email, setEmail] = useState(prefillEmail || "");
  const [name, setName] = useState("");
  const [area, setArea] = useState("");
  const [pw, setPw] = useState("");
  const [pw2, setPw2] = useState("");
  const [error, setError] = useState("");
  const [busy, setBusy] = useState(false);
  const [cooldown, setCooldown] = useState(0);
  const [resetMode, setResetMode] = useState(false);   // reseteo de contraseña en curso
  const invited = !!prefillEmail;

  const reset = () => { setError(""); setPw(""); setPw2(""); };

  // returning from the email-verification link → resume at the credential step
  useEffect(() => {
    const ve = Q.verifiedEmail;
    if (ve) {
      setEmail(ve);
      if (Q.actions.isResetPending && Q.actions.isResetPending(ve)) setResetMode(true);
      const r = Q.actions.login(ve);
      if (r.ok) setStep(r.existing ? "setpw" : "details");
    }
    // eslint-disable-next-line
  }, []);

  // resend cooldown countdown (1s tick while waiting)
  useEffect(() => {
    if (step !== "linksent" || cooldown <= 0) return;
    const t = setTimeout(() => setCooldown((c) => Math.max(0, c - 1)), 1000);
    return () => clearTimeout(t);
  }, [step, cooldown]);

  // auto-advance: the link is confirmed in another tab → localStorage 'storage' event fires here
  useEffect(() => {
    if (step !== "linksent") return;
    const advance = () => {
      const e = email.trim().toLowerCase();
      if (Q.isVerified(e)) {
        if (Q.actions.isResetPending && Q.actions.isResetPending(e)) setResetMode(true);
        const r = Q.actions.login(e);
        toast("Correo verificado ✓", "ok");
        setStep(r.ok && r.existing ? "setpw" : "details");
      }
    };
    const onStorage = (ev) => { if (ev.key === "quiniela_verified_email") advance(); };
    window.addEventListener("storage", onStorage);
    advance(); // in case it was verified before this listener mounted
    return () => window.removeEventListener("storage", onStorage);
  }, [step, email]);

  const continueEmail = async () => {
    setError("");
    const e = email.trim().toLowerCase();
    if (!e) { setError("Ingresa tu correo Quantia."); return; }
    const r = Q.actions.login(e);
    if (!r.ok) { setError(r.error); return; }
    reset();
    if (r.existing && r.needsPassword) { setStep("password"); return; }   // returning → password (already verified at sign-up)
    if (Q.isVerified(e)) { setStep(r.existing ? "setpw" : "details"); return; } // already confirmed on this device
    setBusy(true);                                                        // first time → email a verification link
    const s = await Q.actions.sendVerificationLink(e);
    setBusy(false);
    if (!s.ok) { setError(s.error); return; }
    setStep("linksent");
    setCooldown(60);
  };

  const resendLink = async () => {
    if (cooldown > 0) return;
    setBusy(true);
    const e = email.trim().toLowerCase();
    const s = resetMode ? await Q.actions.sendPasswordReset(e) : await Q.actions.sendVerificationLink(e);
    setBusy(false);
    if (!s.ok) { setError(s.error); return; }
    toast("Enlace reenviado", "ok");
    setCooldown(60);
  };

  // "¿Olvidaste tu contraseña?" → enviar enlace de reseteo
  const forgotPassword = async () => {
    setError("");
    const e = email.trim().toLowerCase();
    if (!e) { setError("Ingresa tu correo."); return; }
    setBusy(true);
    const s = await Q.actions.sendPasswordReset(e);
    setBusy(false);
    if (!s.ok) { setError(s.error); return; }
    setResetMode(true);
    setStep("linksent");
    setCooldown(60);
  };

  const submitPassword = async () => {
    setError("");
    if (!pw) { setError("Ingresa tu contraseña."); return; }
    setBusy(true);
    const r = await Q.actions.verifyPassword(email, pw);
    setBusy(false);
    if (!r.ok) { setError(r.error); return; }
    toast("¡Bienvenido de nuevo!", "gold");
    onDone();
  };

  const submitSetPw = async () => {
    setError("");
    if (pw.length < 4) { setError("La contraseña debe tener al menos 4 caracteres."); return; }
    if (pw !== pw2) { setError("Las contraseñas no coinciden."); return; }
    setBusy(true);
    const r = await Q.actions.setPassword(email, pw);
    setBusy(false);
    if (!r.ok) { setError(r.error); return; }
    if (Q.actions.clearResetPending) Q.actions.clearResetPending();
    fireConfetti();
    toast(resetMode ? "Contraseña restablecida 🎉" : "Contraseña creada 🎉", "gold");
    onDone();
  };

  const submitDetails = async () => {
    setError("");
    if (!name.trim()) { setError("Ingresa tu nombre."); return; }
    if (!area) { setError("Selecciona tu área."); return; }
    if (pw.length < 4) { setError("La contraseña debe tener al menos 4 caracteres."); return; }
    if (pw !== pw2) { setError("Las contraseñas no coinciden."); return; }
    setBusy(true);
    const r = await Q.actions.registerUser({ name, email, area, password: pw });
    setBusy(false);
    if (!r.ok) { setError(r.error); return; }
    fireConfetti();
    toast("¡Listo! Ya estás dentro 🎉", "gold");
    onDone();
  };

  const onKey = (fn) => (e) => { if (e.key === "Enter") fn(); };
  const back = () => { reset(); setResetMode(false); setStep("email"); };

  return (
    <div className="qm-reg-wrap">
      <div className="qm-reg-hero">
        <img className="iso2" src="assets/blob-white.png" alt="" />
        <div style={{ maxWidth: 440, margin: "0 auto", position: "relative", zIndex: 2 }}>
          <div className="qm-brand" style={{ marginBottom: 18 }}>
            <img className="iso" src="assets/iso-white.png" alt="Quantia" style={{ width: 34, height: 34, borderRadius: 10 }} />
            <div className="tag">quantia<small>Quiniela Mundial</small></div>
          </div>
          <div style={{ fontSize: 34, lineHeight: 1.05, marginTop: 8 }}>
            <span style={{ fontSize: 40 }}>⚽</span>
            <div className="q-display" style={{ fontSize: 38, fontWeight: 900, letterSpacing: "-.02em", marginTop: 8, color: "#fff" }}>Quiniela<br />Mundial 2026</div>
          </div>
          <p style={{ color: "rgba(255,255,255,.82)", fontSize: 16, lineHeight: 1.55, marginTop: 14, maxWidth: "32ch" }}>
            Pronostica los marcadores, sube en el ranking y compite con todo el equipo Quantia.
          </p>
        </div>
      </div>

      <div className="qm-reg-card-wrap">
        <div className="qm-reg-card qm-fadein">
          {/* ---------- step: email ---------- */}
          {step === "email" && (
            <>
              <div style={{ fontFamily: "var(--font-head)", fontWeight: 800, fontSize: 20, letterSpacing: "-.01em" }}>Ingresa</div>
              <p style={{ fontSize: 14, color: "var(--fg-3)", margin: "6px 0 20px", lineHeight: 1.5 }}>Usa tu correo corporativo Quantia.</p>
              {error && <div className="qm-error-msg">{error}</div>}
              <div className="qm-field">
                <label>Correo</label>
                <input className={`qm-input ${error ? "err" : ""}`} type="email" value={email} autoFocus={!invited}
                  readOnly={invited} placeholder="nombre@quantia.pe"
                  onChange={(e) => setEmail(e.target.value)} onKeyDown={onKey(continueEmail)} />
                {invited && <span className="qm-readonly-hint"><Icon name="check" size={13} stroke={2.6} />Correo confirmado por invitación</span>}
              </div>
              <button className="qm-btn qm-btn-grad qm-btn-block" style={{ marginTop: 8 }} disabled={busy} onClick={continueEmail}>
                {busy ? "Enviando…" : <>Continuar <Icon name="chevR" size={18} /></>}
              </button>
            </>
          )}

          {/* ---------- step: verification link sent ---------- */}
          {step === "linksent" && (
            <>
              <div style={{ fontFamily: "var(--font-head)", fontWeight: 800, fontSize: 20, letterSpacing: "-.01em" }}>{resetMode ? "Revisa tu correo" : "Verifica tu correo"}</div>
              <p style={{ fontSize: 14, color: "var(--fg-3)", margin: "6px 0 16px", lineHeight: 1.5 }}>
                {resetMode
                  ? <>Te enviamos un enlace a <b>{email}</b> para restablecer tu contraseña. Ábrelo <b>en este dispositivo</b> para crear una nueva.</>
                  : <>Te enviamos un enlace a <b>{email}</b>. Ábrelo <b>en este dispositivo</b> para confirmar tu correo y continuar con tu registro.</>}
              </p>
              {error && <div className="qm-error-msg">{error}</div>}
              <div style={{ display: "flex", gap: 8, alignItems: "center", color: "var(--fg-3)", fontSize: 13, margin: "2px 0 16px" }}>
                <Icon name="mail" size={18} /> Revisa tu bandeja de entrada (y la carpeta de spam).
              </div>
              <button className="qm-btn qm-btn-ghost qm-btn-block" disabled={busy || cooldown > 0} onClick={resendLink}>
                {cooldown > 0 ? `Reenviar enlace en ${cooldown}s` : (busy ? "Enviando…" : "Reenviar enlace")}
              </button>
              <button className="qm-btn qm-btn-ghost qm-btn-block" style={{ marginTop: 8 }} onClick={back}>Usar otro correo</button>
            </>
          )}

          {/* ---------- step: password (returning) ---------- */}
          {step === "password" && (
            <>
              <div style={{ fontFamily: "var(--font-head)", fontWeight: 800, fontSize: 20, letterSpacing: "-.01em" }}>Tu contraseña</div>
              <p style={{ fontSize: 14, color: "var(--fg-3)", margin: "6px 0 20px", lineHeight: 1.5 }}>Ingresando como <b>{email}</b>.</p>
              {error && <div className="qm-error-msg">{error}</div>}
              <div className="qm-field">
                <label>Contraseña</label>
                <input className={`qm-input ${error ? "err" : ""}`} type="password" value={pw} autoFocus
                  placeholder="••••••••" onChange={(e) => setPw(e.target.value)} onKeyDown={onKey(submitPassword)} />
              </div>
              <button className="qm-btn qm-btn-grad qm-btn-block" style={{ marginTop: 8 }} disabled={busy} onClick={submitPassword}>
                {busy ? "Entrando…" : <>Entrar <Icon name="chevR" size={18} /></>}
              </button>
              <button type="button" className="qm-link-btn" style={{ display: "block", margin: "12px auto 2px", background: "none", border: "none", color: "var(--accent, #C2244A)", fontSize: 13, fontWeight: 600, cursor: "pointer" }} disabled={busy} onClick={forgotPassword}>
                ¿Olvidaste tu contraseña?
              </button>
              <button className="qm-btn qm-btn-ghost qm-btn-block" style={{ marginTop: 8 }} onClick={back}>Usar otro correo</button>
            </>
          )}

          {/* ---------- step: set password (legacy / admin-created) ---------- */}
          {step === "setpw" && (
            <>
              <div style={{ fontFamily: "var(--font-head)", fontWeight: 800, fontSize: 20, letterSpacing: "-.01em" }}>{resetMode ? "Crea tu nueva contraseña" : "Crea tu contraseña"}</div>
              <p style={{ fontSize: 14, color: "var(--fg-3)", margin: "6px 0 20px", lineHeight: 1.5 }}>
                {resetMode
                  ? "Verificamos tu correo. Define una nueva contraseña para tu cuenta."
                  : "Esta cuenta aún no tiene contraseña. Crea una para proteger tus pronósticos."}
              </p>
              {error && <div className="qm-error-msg">{error}</div>}
              <div className="qm-field">
                <label>Contraseña</label>
                <input className="qm-input" type="password" value={pw} autoFocus placeholder="Mín. 4 caracteres" onChange={(e) => setPw(e.target.value)} />
              </div>
              <div className="qm-field">
                <label>Repite la contraseña</label>
                <input className="qm-input" type="password" value={pw2} placeholder="••••••••" onChange={(e) => setPw2(e.target.value)} onKeyDown={onKey(submitSetPw)} />
              </div>
              <button className="qm-btn qm-btn-grad qm-btn-block" style={{ marginTop: 8 }} disabled={busy} onClick={submitSetPw}>
                {busy ? "Guardando…" : <>{resetMode ? "Restablecer y entrar" : "Crear y entrar"} <Icon name="chevR" size={18} /></>}
              </button>
              <button className="qm-btn qm-btn-ghost qm-btn-block" style={{ marginTop: 8 }} onClick={back}>Usar otro correo</button>
            </>
          )}

          {/* ---------- step: details (first-time registration) ---------- */}
          {step === "details" && (
            <>
              <div style={{ fontFamily: "var(--font-head)", fontWeight: 800, fontSize: 20, letterSpacing: "-.01em" }}>Crea tu perfil</div>
              <p style={{ fontSize: 14, color: "var(--fg-3)", margin: "6px 0 20px", lineHeight: 1.5 }}>
                Primera vez por aquí. Tu contraseña protege tus pronósticos: nadie más podrá entrar con tu correo.
              </p>
              {error && <div className="qm-error-msg">{error}</div>}
              <div className="qm-field">
                <label>Correo</label>
                <input className="qm-input" type="email" value={email} readOnly />
                <span className="qm-readonly-hint"><Icon name="check" size={13} stroke={2.6} />Correo autorizado</span>
              </div>
              <div className="qm-field">
                <label>Nombre y apellido</label>
                <input className="qm-input" type="text" value={name} placeholder="Ej. Diego Salas" autoFocus onChange={(e) => setName(e.target.value)} />
              </div>
              <div className="qm-field">
                <label>Área / Unidad de negocio</label>
                <div className="qm-chips">
                  {Q.AREAS.map((a) => (
                    <button key={a} type="button" className={`qm-chip-sel ${area === a ? "on" : ""}`} onClick={() => setArea(a)}>{a}</button>
                  ))}
                </div>
              </div>
              <div className="qm-field">
                <label>Contraseña</label>
                <input className="qm-input" type="password" value={pw} placeholder="Mín. 4 caracteres" onChange={(e) => setPw(e.target.value)} />
              </div>
              <div className="qm-field">
                <label>Repite la contraseña</label>
                <input className="qm-input" type="password" value={pw2} placeholder="••••••••" onChange={(e) => setPw2(e.target.value)} onKeyDown={onKey(submitDetails)} />
              </div>
              <button className="qm-btn qm-btn-grad qm-btn-block" style={{ marginTop: 8 }} disabled={busy} onClick={submitDetails}>
                {busy ? "Creando…" : <>Entrar <Icon name="chevR" size={18} /></>}
              </button>
              {!invited && (
                <button className="qm-btn qm-btn-ghost qm-btn-block" style={{ marginTop: 8 }} onClick={back}>Usar otro correo</button>
              )}
            </>
          )}

          <p style={{ fontSize: 12, color: "var(--fg-3)", textAlign: "center", marginTop: 14, lineHeight: 1.5 }}>
            Los pronósticos cierran automáticamente al inicio de cada partido.
          </p>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { RegisterScreen });
