/* Login → window. */
(function () {
  const { useState, useEffect } = React;
  const { useAuth, MotoLogo, GoogleG, Spinner, useTheme } = window;

  const FRASES = [
    "Iglesias más cerca de ti",
    "Cristo viene",
    "Y será predicado este evangelio...",
    "Cristo salva",
    "Búscalo mientras pueda ser hallado",
    // Amor
    "Dios es amor",
    "Tanto amó Dios al mundo",
    "El amor nunca deja de ser",
    "Amarás a tu prójimo",
    "El amor cubre multitud de pecados",
    // Perdón
    "Padre, perdónalos",
    "Si confesamos, Él nos perdona",
    "Perdonados en Cristo",
    "Setenta veces siete",
    "Bienaventurados los misericordiosos",
    // Salvación
    "Jehová es mi pastor",
    "El Señor es mi salvación",
    "Hoy es día de salvación",
    "Por gracia sois salvos",
    "Cree y serás salvo",
    "No hay otro nombre",
    "Yo soy el camino",
    // Redención
    "Nueva criatura en Cristo",
    "Sanados por sus llagas",
    "Justificados por la fe",
  ];

  function Login() {
    const { signInGoogle } = useAuth();
    const { dark } = (typeof useTheme === "function" ? useTheme() : null) || { dark: false };
    const [loading, setLoading] = useState(false);
    const [error, setError] = useState("");

    const bgPanel = dark ? "#0F0F10" : "#FFFFFF";
    const colorTitulo = dark ? "#F0F0F0" : "#3C3C3C";
    const colorFrase = dark ? "#9CA3AF" : "#777";
    const bgBoton = dark ? "#1A1A1A" : "#FFFFFF";
    const colorBoton = dark ? "#F0F0F0" : "#3C3C3C";
    const colorVersion = dark ? "#6B7280" : "#AAA";
    const colorError = dark ? "#FCA5A5" : "#FF4B4B";
    const [fraseIdx, setFraseIdx] = useState(function () {
      return Math.floor(Math.random() * FRASES.length);
    });

    useEffect(function () {
      const t = setInterval(function () {
        setFraseIdx(function (actual) {
          if (FRASES.length <= 1) return 0;
          let next = Math.floor(Math.random() * (FRASES.length - 1));
          if (next >= actual) next += 1; // evita repetir la misma frase
          return next;
        });
      }, 3000);
      return function () { clearInterval(t); };
    }, []);

    const handleLogin = async () => {
      setError("");
      setLoading(true);
      try {
        await signInGoogle();
        // onAuthStateChanged se encarga de navegar; si fue redirect, recarga la página
      } catch (e) {
        console.warn("login error:", e);
        setError("No pudimos conectarte. Intenta de nuevo.");
        setLoading(false);
      }
    };

    return (
      <div
        className="flex flex-col items-center justify-between h-screen px-8 py-14 fade-in"
        style={{ background: bgPanel }}
      >
        <div className="flex-1 flex flex-col items-center justify-center">
          <div className="login-logo-float">
            <MotoLogo size={110} />
          </div>
          <div className="login-logo-shadow" aria-hidden="true" />
          <h1 className="mt-6 text-4xl font-black tracking-tight" style={{ color: colorTitulo }}>CultoRD</h1>
          <div className="mt-2 h-6 flex items-center justify-center overflow-hidden" aria-live="polite">
            <p
              key={fraseIdx}
              className="login-frase font-semibold text-base text-center"
              style={{ color: colorFrase }}
            >{FRASES[fraseIdx]}</p>
          </div>
        </div>
        <div className="w-full pb-6">
          <button
            onClick={handleLogin}
            disabled={loading}
            className="btn-3d w-full h-14 rounded-full flex items-center justify-center gap-3 font-bold text-base uppercase tracking-wide disabled:opacity-70"
            style={{ background: bgBoton, color: colorBoton }}>
            {loading ? <Spinner /> : <GoogleG />}
            {loading ? "Conectando..." : "Iniciar"}
          </button>
          {error && <p className="text-center text-sm font-bold mt-4" style={{ color: colorError }}>{error}</p>}
          <p className="text-center text-xs mt-6 font-semibold" style={{ color: colorVersion }}>
            v1.1 by <a href="https://edservices.com.do/" target="_blank" rel="noopener noreferrer" className="text-inherit no-underline hover:no-underline">Edservices</a>
          </p>
        </div>

        <style>{`
          @keyframes loginLogoFloat {
            0%, 100% { transform: translateY(0) rotate(0deg); }
            50%      { transform: translateY(-14px) rotate(-2deg); }
          }
          @keyframes loginLogoShadow {
            0%, 100% { transform: scale(1); opacity: 0.35; }
            50%      { transform: scale(0.72); opacity: 0.18; }
          }
          .login-logo-float {
            animation: loginLogoFloat 3.2s ease-in-out infinite;
            filter: drop-shadow(0 10px 18px rgba(37, 99, 235, 0.25));
            will-change: transform;
          }
          .login-logo-shadow {
            width: 72px;
            height: 10px;
            margin-top: 6px;
            border-radius: 50%;
            background: radial-gradient(ellipse at center, rgba(37,99,235,0.35) 0%, rgba(37,99,235,0) 70%);
            animation: loginLogoShadow 3.2s ease-in-out infinite;
          }
          @keyframes loginFraseInOut {
            0%   { opacity: 0; transform: translateY(8px); }
            15%  { opacity: 1; transform: translateY(0); }
            85%  { opacity: 1; transform: translateY(0); }
            100% { opacity: 0; transform: translateY(-8px); }
          }
          .login-frase {
            animation: loginFraseInOut 3s ease-in-out both;
            will-change: opacity, transform;
            margin: 0;
          }
          @media (prefers-reduced-motion: reduce) {
            .login-logo-float, .login-logo-shadow, .login-frase { animation: none; }
          }
        `}</style>
      </div>
    );
  }

  window.Login = Login;
})();
