// auth.jsx — Login/signup screen

const AuthScreen = ({ onAuth, lang }) => {
  const [mode, setMode] = React.useState("login");
  const [email, setEmail] = React.useState("");
  const [password, setPassword] = React.useState("");
  const [loading, setLoading] = React.useState(false);
  const [error, setError] = React.useState("");

  const handleSubmit = async (e) => {
    e.preventDefault();
    setLoading(true);
    setError("");

    try {
      if (mode === "login") {
        const { data, error } = await supabase.auth.signInWithPassword({ email, password });
        if (error) throw error;
        if (data.user) onAuth(data.user);
      } else {
        const { data, error } = await supabase.auth.signUp(email, password);
        if (error) throw error;
        if (data.user) onAuth(data.user);
      }
    } catch (err) {
      setError(err.message || "Authentication failed");
    } finally {
      setLoading(false);
    }
  };

  return (
    <div style={{
      minHeight: "100vh",
      display: "flex",
      alignItems: "center",
      justifyContent: "center",
      background: "var(--bg-0)",
      padding: 20,
    }}>
      <div className="card" style={{ maxWidth: 420, width: "100%" }}>
        <div className="card-body" style={{ padding: 32 }}>
          <div style={{ textAlign: "center", marginBottom: 32 }}>
            <div className="brand-mark" style={{ margin: "0 auto 14px", width: 48, height: 48, fontSize: 20 }}>B</div>
            <h1 style={{ margin: 0, fontSize: 22, fontWeight: 600, letterSpacing: "-0.01em" }}>
              BIM Edge Solutions
            </h1>
            <p style={{ color: "var(--fg-2)", fontSize: 13, marginTop: 6 }}>
              {mode === "login" 
                ? (lang === "es" ? "Inicia sesión en tu cuenta" : "Sign in to your account")
                : (lang === "es" ? "Crea tu cuenta" : "Create your account")}
            </p>
          </div>

          <form onSubmit={handleSubmit}>
            <div className="form-row" style={{ marginBottom: 14 }}>
              <label>Email</label>
              <input
                className="input"
                type="email"
                value={email}
                onChange={(e) => setEmail(e.target.value)}
                placeholder="tu@email.com"
                required
                autoFocus
              />
            </div>

            <div className="form-row" style={{ marginBottom: 20 }}>
              <label>{lang === "es" ? "Contraseña" : "Password"}</label>
              <input
                className="input"
                type="password"
                value={password}
                onChange={(e) => setPassword(e.target.value)}
                placeholder="••••••••"
                required
                minLength={6}
              />
            </div>

            {error && (
              <div style={{
                padding: 10,
                marginBottom: 14,
                background: "var(--red-soft)",
                color: "var(--red)",
                borderRadius: "var(--radius-sm)",
                fontSize: 12,
                textAlign: "center",
              }}>
                {error}
              </div>
            )}

            <button
              type="submit"
              className="btn primary"
              style={{ width: "100%", height: 40, justifyContent: "center" }}
              disabled={loading}
            >
              {loading ? "..." : (mode === "login" 
                ? (lang === "es" ? "Iniciar sesión" : "Sign in")
                : (lang === "es" ? "Crear cuenta" : "Sign up"))}
            </button>
          </form>

          <div style={{ textAlign: "center", marginTop: 18, fontSize: 13, color: "var(--fg-2)" }}>
            {mode === "login" ? (
              <>
                {lang === "es" ? "¿No tienes cuenta?" : "Don't have an account?"}{" "}
                <a
                  href="#"
                  onClick={(e) => { e.preventDefault(); setMode("signup"); setError(""); }}
                  style={{ color: "var(--accent)", textDecoration: "none", fontWeight: 500 }}
                >
                  {lang === "es" ? "Crear cuenta" : "Sign up"}
                </a>
              </>
            ) : (
              <>
                {lang === "es" ? "¿Ya tienes cuenta?" : "Already have an account?"}{" "}
                <a
                  href="#"
                  onClick={(e) => { e.preventDefault(); setMode("login"); setError(""); }}
                  style={{ color: "var(--accent)", textDecoration: "none", fontWeight: 500 }}
                >
                  {lang === "es" ? "Iniciar sesión" : "Sign in"}
                </a>
              </>
            )}
          </div>
        </div>
      </div>
    </div>
  );
};

window.AuthScreen = AuthScreen;
